来自JSON文件的Jquery UI自动完成结果

时间:2012-05-30 22:07:01

标签: javascript jquery ajax json autocomplete

我很难成功解析JSON文件以在JQuery UI自动完成中使用

请参阅我的开发页面:http://www.zyredesign.com/autocomplete

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

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

等...

这是我的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;
}
*/

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

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

    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;
        }
    });
相关问题