2016-12-02 101 views
0

我有一個自動完成功能,與本地json源一起工作。鑑於它是16k行代碼,我想將其移至外部json文件。但我似乎無法讓它與外部源文件一起工作。任何人都可以將我指向正確的方向嗎?此時此代碼不起作用,但也不會向控制檯返回任何錯誤。與外部json源jquery自動完成

自動填充腳本

$(function() { 
    $.ajax({ 
    url: "javascripts/airports.json", 
    dataType: "json", 
    success: function(request, response) { 
      var data = $.grep(suggestion, function(value) { 
       return value.city.substring(0, request.term.length).toLowerCase() == request.term.toLowerCase(); 
      }); 
    $('#autocomplete').autocomplete({ 
    minLength: 1, 
    source: data, 
    focus: function(event, ui) { 
       $('#autocomplete').val(ui.item.city,ui.item.country); 
       return false; 
    }, 
    select: function(event, ui) { 
    $('#autocomplete').val(ui.item.name); 
     return false; 
     } 
     }).data("ui-autocomplete")._renderItem = function(ul, item) { 
     return $("<li></li>") 
      .data("ui-autocomplete-item", item) 
      .append("<a>" + item.city + "," + item.country + "</a>") 
       .appendTo(ul); 
      }; 
     } 
    }); 
    }); 

外部數據結構

var suggestion = 
    [ 
    {"id":"1","name":"Goroka","city":"Goroka","country":"Papua New Guinea","iata":"GKA","icao":"AYGA","latitude":"-6.081689","longitude":"145.391881","altitude":"5282","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"} 
    , 
    {"id":"2","name":"Madang","city":"Madang","country":"Papua New Guinea","iata":"MAG","icao":"AYMD","latitude":"-5.207083","longitude":"145.7887","altitude":"20","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"} 
    , 
    {"id":"3","name":"Mount Hagen","city":"Mount Hagen","country":"Papua New Guinea","iata":"HGU","icao":"AYMH","latitude":"-5.826789","longitude":"144.295861","altitude":"5388","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"} 
    , 
    {"id":"4","name":"Nadzab","city":"Nadzab","country":"Papua New Guinea","iata":"LAE","icao":"AYNZ","latitude":"-6.569828","longitude":"146.726242","altitude":"239","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"} 
    , 
    {"id":"5","name":"Port Moresby Jacksons Intl","city":"Port Moresby","country":"Papua New Guinea","iata":"POM","icao":"AYPY","latitude":"-9.443383","longitude":"147.22005","altitude":"146","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"} 
] 

回答

1

你的反應應該是JSON對象(陣列),其中每個項目是idlabelvalue鍵的對象。

您的json文件中的項目沒有labelvalue鍵,所以自動完成功能無法真正顯示它們。

最佳解決方案 - 更改文件/響應的內容以遵循id/label/value結構。

如果你不能做到這一點 - 你可以使用_renderItem函數來創建基於JSON文件的內容,自動完成自己的項目:

$('#autocomplete').autocomplete({ 
    ... 
    _renderItem: function(ul, item) { 
     return $("<li>") 
      .append(item.name) 
      .appendTo(ul); 
    } 
    ... 
}); 
+0

但JSON是工作,當它被作爲本地來源拉入。你是否有理由認爲,爲什麼數據結構只是因爲外部而需要改變? –

+0

說實話我不太確定它是如何工作的,因爲結構不應該與默認的jquery-ui的自動完成一起工作... – Dekel