Understanding and implementing jQuery autocomplete with AJAX source and appendTo

此生再无相见时 提交于 2019-12-28 13:22:10

问题


Below is my attempt at getting appendTo to work with jQuery autocomplete with AJAX source.

I have multiple questions, which will hopefully help many others who are struggling with understanding the correct way to implement autocomplete with and AJAX source.

1) source: function(request, response) {...} What does this do? Why is it needed.

2) What format does function(data){ response($.map (data, function(obj) { return the data in? I realize the data is in JSON format, but what is the point of .map? Is it necessary to do this? Are there benefits?

3a) When using appendTo and renderItem, is it necessary to have the above mentioned success data returned?

3b) Either or, depending on the above data, how do you correctly use appendTo and renderItem to change the formatting and display of your retrieved values?

$(function() {
$( ".find_group_ac" ).autocomplete({
        minLength: 1,
        source: function(request, response) {
            $.ajax({
                url: "welcome/search/",
                data: { term: $(".find_group_ac").val()},
                dataType: "json",
                type: "POST",
                success: function(data){ response($.map
                        (data, function(obj) {
                            return {
                            label: obj.name + ': ' + obj.description,
                            value: obj.name,
                            id: obj.name
                };}));}
            });
        }
    }).data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
                .appendTo( ul );
        };
});

This might seem like a lot to answer, but I'm sure it will be valuable to many javascript newbies and certainly myself.


回答1:


source: function(request, response) {...} What does this do? Why is it needed.

Since you're doing a custom AJAX POST to get the data, you must specify a function that calls the response callback with the desired autocomplete candidates.

In the simplest use case, you can just supply a string to the source parameter, and the widget will issue a GET request against that URL with an appended ?term=(term). Since you're doing a POST and sending up a different term, you must use the function version of source.

PS: You should supply the $.ajax call with request.term instead of $(".find_group_ac").val()


What format does function(data){ response($.map (data, function(obj) { return the data in? I realize the data is in JSON format, but what is the point of .map? Is it necessary to do this? Are there benefits?

The autocomplete widget expects an array data source who's items meet one of the following requirements:

  1. The item must be a single string, or:
  2. The item must be an object with a label property, a value, property, or both.

With this in mind, if you're using a server-side resource whose JSON is not formatted in this way, you have to transform the data to meet those specifications before supplying it to the response function. The common way to do this is to use $.map, which iterates over an array and transforms each element.


When using appendTo and renderItem, is it necessary to have the above mentioned success data returned?

No, but they are often used together.

Say you have an extra property (like description) that you want to display in the candidate list. In this case, you might transform the server-side result into the format autocomplete expects (to include label and value but still include description), but you also want to display the description property. In this case, you'll need to overload _renderItem.


Either or, depending on the above data, how do you correctly use appendTo and renderItem to change the formatting and display of your retrieved values?

If the questions asked above this ones are answered adequately in this answer, then all I should need to do is post some code that brings the concepts together:

$( ".find_group_ac" ).autocomplete({
    minLength: 1,
    source: function(request, response) {
        $.ajax({
            url: "welcome/search/",
            data: { term: $(".find_group_ac").val()},
            dataType: "json",
            type: "POST",
            success: function(data) { 
                response($.map(data, function(obj) {
                    return {
                        label: obj.name,
                        value: obj.name,
                        description: obj.description,
                        id: obj.name // don't really need this unless you're using it elsewhere.
                    };
                }));
            }

        });
    }
}).data( "autocomplete" )._renderItem = function( ul, item ) {
    // Inside of _renderItem you can use any property that exists on each item that we built
    // with $.map above */
    return $("<li></li>")
        .data("item.autocomplete", item)
        .append("<a>" + item.label + "<br>" + item.description + "</a>")
        .appendTo(ul);
};

The examples on jQueryUI's documentation page for autocomplete are actually quite extensive and could be helpful. Specifically, be sure to check out:

  • Custom data and display
  • Remote JSONP data source


来源:https://stackoverflow.com/questions/11729588/understanding-and-implementing-jquery-autocomplete-with-ajax-source-and-appendto

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