jQuery 自动完成在第一次尝试时不起作用


jQuery autocomplete not working for the first attempt

>我试图在我的程序中实现动态自动完成。它在第一次输入后工作正常。但它没有显示第一次尝试的建议。但是,服务器正在响应自动完成所需的源。这是我的代码。

       $('.autocomplete').live('keyup', function(){
        $this = $(this);
        var search = $this.val();
        $.ajax({
            url:'/package/index/search/keyword/'+search+'/format/json',
            async: false,
            success: function(res){
                //console.log(res.options);
                //console.log(res.defined_ids);
                staticObject = res.defined_ids;
                $this.autocomplete({
                    source: res.options
                });
            }
        });            
    });

服务器端代码是

    $keyword = $this->_getParam('keyword');
    $elementDetailModel = new Package_Model_ElementDetail();
    $arr = $elementDetailModel->searchElementDetail($keyword);
    $this->view->options = $arr['options']; // returns in the format array("test2","my new test", "night stay in delux room")
    $this->view->defined_ids = $arr['defined_ids']; // returns in the format array(21::21=>"test2", 22::22=>"my new test", 24::24=>"night stay in delux room")

当我在Firebug中控制台登录defined_ids和选项时,当我在文本字段中键入" t"时,我得到了以下响应。
选项:

["Test2", "我的新测试", "豪华客房住宿"]

defined_ids:

对象 { 21::21="test2", 22::22="我的新测试", 24::24="豪华客房住宿"}

任何帮助都是可观的。提前谢谢。

Firebug 显示的格式不是 JSON 的格式。它是一个数组,使用索引进行访问。

显示输出时,请确保先json_encode()数组,然后再显示它。

例如,关于问题,最终数组应如下所示

$array['options'] = array("test2", "my new test", "night stay in room");
//Then you should echo the encoded the array to json
echo json_encode($array);

接下来,确保视图已关闭此请求。

您可能忘记指定上下文服务器。在控制器的_init()方法中,添加:

$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('actionName', 'json')
            ->initContext();

并确保将actionName替换为操作控制器名称。

然后,$this->view->options = $arr['options']将自动转换为有效的 json 格式。

有关 AjaxContext 的更多信息,请参见手册。