JQuery UI自动完成功能立即消失

时间:2014-03-17 09:21:38

标签: javascript jquery jquery-ui autocomplete

使用JQuery UI的自动填充时,下拉结果似乎永远不会出现。但是,在调试时,列表会在消失之前显示少量语句。我的代码如下:

HTML:

<input type="text" placeholder="search" class="myautocomplete" />
<script>
    $(document).load(function(){initializeAutocomplete()});
</script>

使用Javascript:

function initializeAutocomplete() {
    $('.myautocomplete').autocomplete({delay: 300, minLength: 2, source: autocomplete});
}

function autocomplete(request, responseCallback) {
    var dataUrl = "http://something.com/Suggestions.json?search_string=" + request.term;
    var suggestions = [];
    $.getJSON(dataUrl, function(json) {
        $.each(json.AutoSuggestions, function(index) {
            suggestions.push(this.SearchTerm);
        });
    });
    responseCallback(suggestions);
}

是什么导致自动填充列表立即消失?

1 个答案:

答案 0 :(得分:2)

因为getJSON是异步的,所以当数组为空时调用responseCallback函数,在getJSON函数内的每个循环之后移动函数。

尝试更改它:

function initializeAutocomplete() {
    $('.myautocomplete').autocomplete({delay: 300, minLength: 2, source: autocomplete});
}

function autocomplete(request, responseCallback) {
    var dataUrl = "http://something.com/Suggestions.json?search_string=" + request.term;
    var suggestions = [];
    $.getJSON(dataUrl, function(json) {
        $.each(json.AutoSuggestions, function(index) {
            suggestions.push(this.SearchTerm);
        });
        responseCallback(suggestions);
    });
}