2012-05-30 41 views
0

我成功地解析JSON文件將jQuery UI自動完成中使用從JSON文件jQuery UI的自動完成結果

請參閱我的dev頁有很大的難度: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

您爲source:attribute提供的函數不返回值。 $ .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; 
     } 
    });