Combining a local source and remote source in jquery ui autocomplete

落爺英雄遲暮 提交于 2020-01-14 10:09:17

问题


I included locally in javascript a list of commonly used terms, and then I would also like to get json response from the server through ajax response. How can it be done?

var projects = ["apple", "orange"];

$('#search').autocomplete({
    source: projects
});

then append the result from ajax?


回答1:


The way you would go about this would be to combine the results you get back from the server with the local results array. You can accomplish this by passing a function to the source option of autocomplete:

There are three steps you'll have to perform:

  1. Make the AJAX request and get results from the server.
  2. Filter the local array
  3. Combine the results

This should be pretty simple. Something like this would work:

$("input").autocomplete({
    source: function(request, response) { 
        /* local results: */
        var localResults = $.ui.autocomplete.filter(localArray, request.term);

        /* Remote results: */
        $.ajax({
            /* AJAX options omitted... */
            success: function(data) {
                /* Process remote data using $.map, if necessary, then concatenate local
                 * and remote results. 
                 */
                response(data.concat(localResults));
            }
        });
    }
}); 

I've worked up a full example here: http://jsfiddle.net/FZ4N4/



来源:https://stackoverflow.com/questions/14043608/combining-a-local-source-and-remote-source-in-jquery-ui-autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!