簡體   English   中英

來自JSON文件的Jquery UI自動完成結果

[英]Jquery UI autocomplete results from JSON file

我在成功解析JSON文件以在JQuery UI自動完成中使用時遇到了很大困難

請參閱我的開發頁面: http//www.zyredesign.com/autocomplete

JSON沒有像我希望的那樣組織,因為項目鍵是ID,例如:

{“140”:“Abarth”,“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;
}
*/

任何幫助將不勝感激,謝謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM