简体   繁体   中英

How to use a JSon array in a JQuery autocomplete

I have a JSon array which is as follows:

[{"country":"FR","id":2,"latitude":-34.27175846153846,"longitude":54.16125384615385,"postcode":"00000","region1":"DOM-TOM","region2":"Terres australes et antarctiques","region3":"Crozet","region4":"","version":null},{"country":"FR","id":3,"latitude":46.203635000000006,"longitude":5.20772,"postcode":"01000","region1":"Rhône-Alpes","region2":"Ain","region3":"Bourg-en-Bresse","region4":"Bourg-en-Bresse","version":null}, ...

I am trying to use this array as a source for a JQuery autocomplete. Here is what I attempted:

$(function() {
    $("#postcode").autocomplete({
        source : function(request, response) {
            var firstChars = $("#postcode").attr("value");
            $.getJSON("/kadjoukor/geolocations", {
                postcodeFirstChars : firstChars
            }, function(data) {
                console.log(data.postcode);
                response(data.postcode);
            });
        },
        minLength : 3,
    });
});

Here is the html:

<input type="text" name="member.geolocation.postcode" value="" id="postcode" placeholder="Code postal" /> 

I want to display the postcode variable from this JSon array. Can anyone please help?

You should transform the the result array to label-value pairs. In your case in can be like

source : function(request, response) {
        var firstChars = $("#postcode").attr("value");
        $.getJSON("/kadjoukor/geolocations", {
            postcodeFirstChars : firstChars
        }, function(data) {
            console.log(data.postcode);
            response($.map(data, function (item) {
                    return {
                        label: item.postcode,
                        value: item.postcode
                    };
                }));
        });
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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