开发者

parsing json in jquery autocomplete

开发者 https://www.devze.com 2023-02-12 00:29 出处:网络
I\'ve used Simon Whatley\'s code for the autocomplete plugin. Now, I need help in parsing a jSON data. Here is my code:

I've used Simon Whatley's code for the autocomplete plugin. Now, I need help in parsing a jSON data. Here is my code:

    $("#country").autocomplete("data/country.cfm",{
        minChars:1,
        delay:0,
        autoFill:false,
        matchSubset:false,
        matchContains:1,
        cacheLength:10,
        selectOnly:1,
        dataType: 'json',
        extraParams: {
                format: 'json'
        },
        parse: function(data) {
            var parsed = [];
            for (var i = 0; i < data.length; i++) {
                 parsed[parsed.length] = {
                data: data[i],
                value: data[i].NAME,
                result: data[i].NAME
                 };
           开发者_C百科 } 
            return parsed;
        },
        formatItem: function(item) {
            return item.NAME;
        }
   });

For example, I get this as my jSON string:

[{"name":"country1"},{"name":"country2"},{"name":"country3"}]

What I like to get as results, of course, are the values country1, country2, country3. However, what I get right now in the textbox when I type (e.g. I type "cou") is "undefined". If I click that, what shows in the textfield is the whole string [{"name":"country1"},{"name":"country2"},{"name":"country3"}].

I've also tried these but still not working: jquery autocomplete, how to parse a json request with url info? jquery autocomplete with json response

Help please. Thanks!


You can just simply use

var countries = JSON.parse(data);

Since you're using jQuery though, it's a bit safer to use jQuery.parseJSON() in case the browser doesn't have a native parser:

var countries = jQuery.parseJSON(data);
0

精彩评论

暂无评论...
验证码 换一张
取 消