【问题标题】:Populating my jquery autocomplete with contents of an ajax call to cakephp使用对 cakephp 的 ajax 调用的内容填充我的 jquery 自动完成功能
【发布时间】:2012-11-06 15:52:06
【问题描述】:

我有一个输入字段,我将其变成 jqueryUI 自动完成功能:

$( "#autocomplete" ).autocomplete({
    autoFocus: true,
    source: mylist
 });

mylist 变量只是数组格式 ['Value1','Value2,'Blah'] 的字符串,我最初只是硬编码到脚本中。

现在我希望 mylist 变量是对我的 cakephp 应用程序中的函数的 ajax 调用的结果。函数基本如下,就是把所有的数据抓取成一个list,然后json编码。

public function source() {
    $this->layout = 'ajax';
    $countries=$this->Country->find('list',array('fields'=>'Country.country'));
    ChromePhp::log($countries);
    echo json_encode($countries);
}

这个输出:

{"1":"Afghanistan","2":"Albania ","3":"Algeria ","5.. 

我的问题是将这个函数的输出(最终在 ajax 成功回调中作为“数据”)转换为正确的格式,以放入自动完成的选项数组中。

我可以在控制台记录每个值,但我很难过。基本上以正确的语法抓住稻草。

$.ajax({
    type: "GET",
    dataType: "json",
    url: "/source/",
    success: function(data){
        /*
        magic array string creation code would go here instead of my code below...
        */
        $.each(data, function(i, item) {
            console.log(item);
        });
        console.log('data',data);


    }
})

【问题讨论】:

    标签: ajax jquery-ui autocomplete cakephp-2.1


    【解决方案1】:

    如果您以正确的格式提供内容,自动完成插件可以为您完成很多工作。

    我首先将$countries 变量重新索引为从0 开始。您可以为此使用array_values() 函数:

    echo json_encode(array_values($countries));
    

    这应该为您提供格式如下的 JSON:

    ['Afghanistan','Albania','Algeria',...]
    

    然后您可以将自动完成代码中的源属性更改为源操作的 url。

    $( "#autocomplete" ).autocomplete({
        autoFocus: true,
        source: "/your_controller/source"
    });
    

    自动完成插件不会为您过滤结果,而是将查询字符串添加到带有 term 字段(例如 /your_controller/source?term=foo)的 url,因此您需要修改您的 find()使用方法。

    $countries = $this->Country->find('list', array(
        'fields' => 'Country.country',
        'conditions' => array(
            'Country.country LIKE' => $this->request->query['term'] . '%'
        )
    ));
    

    您可以在API Documentation 的自动完成中阅读更多关于source 选项可以接受的不同类型的信息。

    【讨论】:

    • 究竟为什么这个网站是我一直以来最喜欢的开发网站 :) 谢谢。
    猜你喜欢
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多