简体   繁体   中英

jQuery autocomplete not working for the first attempt

I have tried to implement dynamic autocomplete in my program. It is working perfectly after first input. But it doesn't show suggestions for the first attempt. However, server is responding the required source for autocomplete. Here is my code.

       $('.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
                });
            }
        });            
    });

Server side Code is

    $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")

when I console logged defined_ids and options in firebug, I got following response when I typed 't' in the text field.
options:

["test2", "my new test", "night stay in delux room"]

defined_ids:

Object { 21::21="test2", 22::22="my new test", 24::24="night stay in delux room"}

Any help would be appreciable. Thanks in advance.

The format displayed from the firebug, is not that of a JSON. It is an array, which are accessed using indices.

When you are displaying the output, make sure you json_encode() the array first, then display it.

For example, with respect to the question, you final array should look something like this

$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);

Next, make sure you views are turned off this request.

You probably forgot to specify the context sever-side. In you controller's _init() method, add:

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

and make sure to replace actionName by you action controller name.

Then, $this->view->options = $arr['options'] will automatically be converted in a valid json format.

More information about AjaxContext here in the manual .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM