0

我在成功解析 JSON 文件以在 JQuery UI 自动完成中使用时遇到了很大的困难

请查看我的开发页面:http ://www.zyredesign.com/autocomplete

JSON的组织不如我希望的那样好,因为项目键是ID,例如:

{“140”:“阿巴斯”,“375”:“讴歌”}

ETC....

这是我的 javascript 尝试:

$(document).ready(function() {


    $('#cars').autocomplete({
        source: function()
        {


            $.getJSON('json.json', function(data)
            {
                cars_array = new Array();

                $.each(data, function(k, v) { 

                    cars_array.push(v);

                 })

                alert( cars_array);

                return cars_array;
            })


        },
        minLength: 3,
        focus: function( event, ui ) {},
        select: function( event, ui ) {
            $('#suggestions').html(ui);

            return false;
        }
    });

});

/*
function get_json()
{
var items = new Array();

$.getJSON('json.json', function(data) {
  var items = [];


  alert(  eval ("(" + data + ")") ); 

 // $.each(data, function(key, val) {
    //items.push('<li id="' + key + '">' + val + '</li>');

 // });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

return items;
}
*/

任何帮助将不胜感激,谢谢!

4

1 回答 1

2

您为 source: 属性提供的函数不返回值。$.get() 函数可以,但不会到达 source 属性。

    source: function()
    {
        $.getJSON('json.json', function(data)
        {
            cars_array = new Array();
            $.each(data, function(k, v) { 
               cars_array.push(v);
            })
            return cars_array;
        })
        //You need to return something here
    }

此外,您以同步模式使用对 json 文件的异步调用可能是一个问题。换句话说,考虑一下:

    $.getJSON('json.json', function(data)
    {
        cars_array = new Array();
        $.each(data, function(k, v) { 
           cars_array.push(v);
        })

        //Now you definitely have the cars so you can do the autocomplete
        $('#cars').autocomplete({
            source:cars_array,
            minLength: 3,
            focus: function( event, ui ) {},
            select: function( event, ui ) {
            $('#suggestions').html(ui);
            return false;
        }
    });
于 2012-05-30T22:22:31.553 回答