【问题标题】:Jquery UI autocomplete results from JSON file来自 JSON 文件的 Jquery UI 自动完成结果
【发布时间】:2012-06-05 04:46:57
【问题描述】:

我很难成功解析 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;
}
*/

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

【问题讨论】:

    标签: javascript jquery ajax json autocomplete


    【解决方案1】:

    您为 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;
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2017-12-03
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多