Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - Understanding and implementing jQuery autocomplete with AJAX source and appendTo

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...