jQuery自动完成功能在控制台中显示结果,但不是下拉列表

时间:2012-05-01 20:30:15

标签: jquery json jquery-ui autocomplete

我正在使用jQuery UI的自动完成功能,在这种情况下,我的结果显示在控制台中作为JSON就好了,但没有自动完成菜单出现。有什么想法吗?

var cct = $('input[name=csrf_token_name]').val();

$('input[name=search]').autocomplete({
    source: function() {
        $.ajax({
          type: 'POST',
          url: '<?php echo site_url('ajax/getSearchKeywords'); ?>',
          dataType: 'json',
          data: { search:$('input[name=search]').val(), csrf_token_name: cct },
          success: function(data) { console.log(data); },
          error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown) }
        });
    },
    appendTo: 'section.search',
    minLength: 2,
    delay: 0,
    selectFirst: true
});

另外,当我开始在2个字符后面输入时,jQuery会在DOM中创建以下元素:

<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role="listbox" aria-activedescendant="ui-active-menuitem" style="z-index: 101; top: 0px; left: 0px; display: none; "></ul>

控制台显示(根据我搜索的内容而改变):

["0j0sZsOqy0", "z57RuUeVnb", "nF4YFR6pMk"]

这是我的getSearchKeywords函数:

public function getSearchKeywords()
{
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');

    echo json_encode($this->tasks->getSearchKeywords($this->input->post('search')));
}

1 个答案:

答案 0 :(得分:2)

您没有正确使用回调功能。

你的源函数应该有2个参数 - 一个包含该术语的对象,以及一个将结果传递给的回调函数。通过ajax检索术语后,需要调用回调函数。

类似的东西:

function getTerms(term_obj, callback) {
        $.ajax({
          type: 'POST',
          url: '<?php echo site_url('ajax/getSearchKeywords'); ?>',
          dataType: 'json',
          data: { search:term_obj.term, csrf_token_name: cct },
          success: function(data) { callback(data) },
          error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown) }
        });


}

然后,传递该函数^^作为自动完成器的源。

相关问题