开发者

Problem with using formatted JSON data as jQuery-UI Autocomplete source

开发者 https://www.devze.com 2023-02-15 06:28 出处:网络
Hey, folks. I\'m pretty new to jQuery and javascript in general and I\'m having a bit of trouble with the Autocomplete widget found in jQuery-ui.

Hey, folks. I'm pretty new to jQuery and javascript in general and I'm having a bit of trouble with the Autocomplete widget found in jQuery-ui.

I'm trying to get a whole bunch of JSON data which I have pulled from a mySQL database and formatted with PHP in a rather specific way. I then want to format portions of this data into an array which is then used as the source for the autocomplete widget.

Here is the autocomplete bit:

var dogs = [];
$( '.dogs' ).autocomplete({
    source: dogs,
    delay: 10,
});

Pretty basic, and I can get it to work as expected. When I start in with the Ajax is when things get confusing.

My JSON data is formatted "0":{"actu":"Actual Name0","disp":"Display Name0"},"1":{"actu":"Actual Name1","disp":"Display Name1"}, etc. such that each 'dog' has two names and a unique, numerical ID to make it easier to loop through the data.

var dogNames = [];
$.getJSON("dataconditioner.p开发者_Go百科hp", function(json) {

    for (var k in json){
        dogNames[k] = json[k]["disp"];
    }
    $( '.dog' ).autocomplete( "option", "source", dogNames);
});

The goal here is to get all of the display names into a 1D array and then have the autocomplete use that array as its source. The array seems formed correctly as when I use alert() to print out results within the callback, I get the expected results. But for whatever reason the autocomplete does nothing when I use this array as its source.

Thanks in advance.


You want to use dogNames.push(json[k].disp) to populate your array.

Right now your code is treating dogNames as an associative array or object, which cannot be used as the source option to autocomplete. This is because the value of "k" is a string, not an integer. The order of the autocomplete source array is not relevant, so don't bother trying to index into the array you're creating. Just push each element onto it and let the plugin do the heavy lifting for you.


Get dognames as comma separated string and try as this

 $( '.dog' ).autocomplete( "option", "source", dogNames.split(','));
0

精彩评论

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

关注公众号