【问题标题】:Cannot display returned json data in CodeIgniter using jQuery autocomplete无法使用 jQuery 自动完成在 CodeIgniter 中显示返回的 json 数据
【发布时间】:2012-12-26 22:16:36
【问题描述】:

我正在尝试将一些 AJAX 代码从独立文件移动到我的控制器中的函数中,但似乎无法让它在视图的自动完成函数中显示 JSON 数据。我已经通过直接访问函数 URL 验证了该函数确实返回了 JSON 编码的数据。

从我的角度来看,这是我的 JavaScript:

<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
    source: <?php echo base_url() . 'admin/lookup_tmdb_movie_titles'; ?>
    select: function(event, ui){
        $("#title").val(ui.item.title);
        $("#year").val(ui.item.year);
        $("#imdb_link").val(ui.item.imdb_link);
    },
    minLength:2,
    position: {
        my: "left top",
        at: "left bottom",
        collision: "none",
        of: "#title.ui-autocomplete-input.ui-autocomplete-loading"
    }
};
$("#title").autocomplete(ac_config);
});
</script>

这是管理控制器中的功能(我只是使用硬编码的测试数据,直到我让它正常工作):

function lookup_tmdb_movie_titles()
{
    $term = 'test';

    // TEST DATA
    $title['title'] = 'test';
    $title['label'] = 'test (2012)';
    $title['value'] = 'test';
    $title['year'] = '2012';
    $title['imdb_link'] = 'testlink';
    $matches[] = $title;

    // convert into JSON format and output
    $matches = array_slice($matches, 0, 5);

    $this->output->set_output( json_encode($matches) );
}

我还尝试了以下两种方式输出 JSON,如果我直接通过 URL 转到函数,所有这些方式都可以,但在视图本身中都不起作用。

    print json_encode($matches);

    $data['json'] = json_encode($matches);
    $this->load->view('admin/json_view', $data);

我在 StackOverflow 和 Google 上查看了很多帖子(因此上面有不同的输出方法),但似乎还没有解决问题。

【问题讨论】:

  • 您是否使用 firebug 或任何其他调试器来检查发送和接收的 Ajax 数据
  • 刚刚启用了 Firebug,发现一个简单的语法错误导致源无法加载。感觉自己像个白痴。谢谢艾哈迈德!现在一切都好!

标签: ajax json jquery-ui codeigniter jquery-ui-autocomplete


【解决方案1】:

首先你应该试试这个:

  source: "<?php echo site_url(admin/lookup_tmdb_movie_titles); ?>"

那么这可能是:

function lookup_tmdb_movie_titles()
{
    $term = 'test';

    // TEST DATA
    $title['title'] = 'test';
    $title['label'] = 'test (2012)';
    $title['value'] = 'test';
    $title['year'] = '2012';
    $title['imdb_link'] = 'testlink';
    $matches[] = $title;

    // convert into JSON format and output
    $matches = array_slice($matches, 0, 5);
   var_dump($matches); //comment this if everythings ok
// echo json_encode($matches);  ->uncomment this if everythings ok

}

然后打开firebug启动ajax请求并在控制台查看响应。

【讨论】:

  • 是的,就是这样,简单的语法错误!啊!也感谢 Ahmed 推荐 Firebug。
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多