简体   繁体   English

jQuery自动完成ajax请求不会更新

[英]jQuery autocomplete ajax request doesn't update

I have this code to do jquery autocomplete: 我有以下代码来执行jQuery自动完成功能:

var suggestions = [];

function complete(){
    // jQuery Autocomplete
    $('#q').autocomplete({
        source: suggestions,
        select: function(event, ui) {
            window.location = '/play/' + ui.item.display_id;
            event.preventDefault();
        },
        focus: function (event, ui) {event.preventDefault();}
    }).bind('focus', function(){
        if($(this).val().length > 0){
            $(this).autocomplete("search");
        }
    }).autocomplete('instance')._renderItem = function(ul, item){
        return $("<li>").append("<a href='/play/" + item.display_id + "' class='row'>\
                <span class='col-sm-3'><img height=\"50px\" src=\"" + item.icon + "\"></span>\
                <span class='col-sm-9'><p>" + item.title + "</p><p style=\"white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:1.3rem;\">" + item.short_description + "</p></span>\
            </a>")
            .appendTo(ul);
    };
}

I then have this that makes an ajax request and returns new results: 然后,我收到了一个发出ajax请求并返回新结果的代码:

gs.search.suggest($this.val(), function(err, data){
    if(err){return;}
    suggestions = data;
    complete();
});

Here is what it looks like within the page: 这是页面中的外观:

var delay = null;
$('#q').on('keypress', function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        search($(this).val());
    }else{
        $this = $(this);
        clearTimeout(delay);
        delay = setTimeout(function() {
            gs.search.suggest($this.val(), function(err, data){
                if(err){return;}
                suggestions = data;
                complete();
            });
        }, 200);
    }
});

It works, but not as I type. 它有效,但是在我键入时不起作用。 When I type something I then have to remove focus from the input box, and focus back on the input box for the results to display. 当我键入某些内容时,我必须从输入框中移出焦点,然后再重新聚焦在输入框中以显示结果。 I need them to display right away (as I type). 我需要它们立即显示(输入时)。

So, something like this lets you use a function as the source, rather than a array which you try to fill in sort of behind autocomplete's back: 因此,类似这样的东西使您可以使用函数作为源,而不是试图填充自动完成背后的数组:

$('#q').autocomplete({
    ...
    source: function(request, response) {
          gs.search.suggest(request,
              function(err, data) {
                  if (err) {
                      /* do something with err condition */
                  } else {
                      /* may need to reformat data here? */
                      response(data);
                  }
              }
          );
      }
      ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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