2012-02-18 54 views
2

我非常努力地嘗試使用jQuery UI自動完成插件。我看了一些演示,但我仍然無法讓它正常工作。我想要做的是從我的json文件中調用名爲destination.json的數據。jQuery UI自動完成從json文件中獲取數據

這是我到目前爲止有:

$("#autocomplete").autocomplete({ 
    source: function(request, response) { 
     $.ajax({ 
      url: "data/destination.json", 
      dataType: "json", 
      success: function(data) { 
       response(data.destinations); 
      } 
     }); 
    } 
}); 

&的HTML

<div class="left">Destination</div> 
<div class="right"><input name="autocomplete" type="text" size="27" id="autocomplete"/></div> 
<div class="clear"></div> 

我在做什麼錯?謝謝!

&的JSON

{ 
"destinations": [ 
    { 
     "value": "Oceania and Australia", 
     "label": "Australia & South Pacific" 
    }, 
    { 
     "value": "Australia", 
     "label": "Australia" 
    }, 
    { 
     "value": "Brisbane", 
     "label": "Brisbane-Australia" 
    }, 
    { 
     "value": "GoldCoast", 
     "label": "GoldCoast-Australia" 
    }, 
    { 
     "value": "SunshineCoast", 
     "label": "SunshineCoast-Australia" 
    } 
] 
} 
+0

這個代碼會發生什麼?你在控制檯中看到任何錯誤嗎? – ShankarSangoli 2012-02-18 05:55:03

+0

你有什麼錯誤嗎?當你自己運行ajax函數時會發生什麼?它返回什麼? – xanderer 2012-02-18 05:56:39

+1

我沒有看到發送數據到json文件和響應函數的任何代碼! – 2012-02-18 05:58:44

回答

-1

源可以直接指向將得到的JSON響應的URL。

$("#ac").autocomplete({ 
    source: "data/destination.json", 
    minLength: 2, 
    select: function(event, ui) { 
     if (ui.item) { 
      // do something on successful select of an item 
     } 
    } 
}); 

哦,並且json響應必須採用特定的格式。

[{ 
    "id": 1234, 
    "label": "Australia & South Pacific", 
    "value": "Oceania and Australia", 
    "extrastuff1": "hello", 
    "extrastuff2": "jin" 
}, {...}] 

我想你會得到id,label,value。只是FYI,你也可以發回額外的信息,並在JavaScript訪問它,如$("#log").html(ui.item.extrastuff1);

+0

我還是有點感到困惑的是什麼意思..對不起,我真的沒有太多的經驗與這個和即時尋找教程不是很有幫助 – user713075 2012-02-18 06:21:29

+0

所以標籤和價值是不夠的? – user713075 2012-02-18 06:28:42

+0

標籤和價值應該是足夠的。 .bat,data/destination.json是一個靜態文件嗎? – 2012-02-18 06:40:33