0
我想在返回JSON數組的服務上使用JQuery自動完成(在mimetype應用程序/ json中)。 我的開發基於此示例:http://jqueryui.com/autocomplete/#remote-jsonp,它從Geonames中檢索JSON。在GEONAMES例如正確的JSON是一樣的東西JSON數組的JQuery自動完成
{"totalResultsCount":8387672,"geonames":[{"countryName":"Iran","adminCode1":"23","fclName":"mountain,hill,rock,... ","countryCode":"IR","lng":49.133333,"fcodeName":"mountain","toponymName":"Kūh-e Zardar","fcl":"T","name":"Kūh-e Zardar","fcode":"MT","geonameId":1,"lat":32.983333,"adminName1":"Lorestān","population":0}]}
不幸的是我服務爲我提供了只有以下:
["berlin; berlin-steglitz","berliner festspiele"]
我試圖解析陣列爲好,但即使我得到正確的Http 200和我看到響應是正確的,我無法解析數組或使用它。 Jquery中的.ajex函數「成功」不會被調用(我猜是因爲它期望一個json內容並檢索文本),而「complete」返回的是一個沒有方法的數據對象來檢索responseText或者數據。 我無法使用requesttype「text」,因爲該服務位於另一個域中,我打破了跨域模式。我的代碼如下。
$(function() {
$("#searchinput").autocomplete(
{
source : function(request, response) {
$.ajax(
{
url : "http://Mybackendservice.com/",
dataType : "jsonp",
data : {
query : request.term
},
complete : function(data) {
console.log(data);
for(i=0;i<data.length;i++){
console.log(data[i].parametername); /// do whatever you want here.
};
response($.map(data, function(n,i) {
return {
label : n,
value : i
}
}));
}
});
},
minLength : 2,
select : function(event, ui) {
console.log(ui.item ? "Selected: " + ui.item.label
: "Nothing selected, input was " + this.value);
},
open : function() {
$(this).removeClass("ui-corner-all").addClass(
"ui-corner-top");
},
close : function() {
$(this).removeClass("ui-corner-top").addClass(
"ui-corner-all");
}
});
});
任何人有如何處理解析這樣的一個數組的問題的一些建議?
當你使用'sucess'而不是'complete'時會發生什麼? (這裏應該是'成功')。你是否也在提出跨域請求?否則,你不應該需要'jsonp'。 – 2013-03-25 17:09:05
@安德魯·惠特克我提到它沒有成功。並且我正在使用跨域請求,否則我只想去「文本」 – 2013-03-25 17:10:56
「failure」方法是否得到執行?如果是這樣,它是否會給你一個錯誤信息?另外,你確定你正在使用的服務器支持JSONP嗎? – 2013-03-25 17:12:05