[英]Javascript error parsing http response
我正在嘗試使用Javascript解析www.skiddle.com API的響應:
$.ajax({
url: 'http://www.skiddle.com/api/v1/events/search/?api_key=myapikey' + '&latitude=' + lat + '&longitude=' + long + '&radius=800&eventcode=LIVE&order=distance&description=1',
type: "GET",
success: function(response) {
var list = [];
$(response).find("results").each(function() {
var el = $(this);
var obj = {
"eventname": el.find("eventname").text(),
"imageurl" : el.find("imageurl").text(),
};
list.push(obj);
});
響應實際上具有一個results
屬性,該屬性具有數組中的一個元素:
{error: 0, totalcount: "1", pagecount: 1, results: Array(1)}
但我似乎無法正確解析, $(response).find("results")
返回任何內容。
如果您確定響應中將有一個result
數組屬性,則可以簡單地使用response.results
為數組提供屬性。
success: function(response) {
$.each(response.results,function(indx,item){
console.log(item);
var obj = {
eventname: item.eventname,
imageurl : item.imageurl
};
list.push(obj);
});
}
假設list
是前面定義的數組。
另外,如果您確定數組中只有一項,則不需要循環,可以通過response.results[0]
success: function(response) {
if (response.results.length>0) {
var obj = { eventName: response.results[0].eventname,
imageurl : response.results[0].imageurl };
list.push(obj);
}
}
我還注意到,您的新對象與要迭代的對象具有相同的屬性名稱。 在這種情況下,您只需添加相同的對象
list.push(response.results[0]);
當然,這將按原樣添加第一個項目,這意味着,如果該項目具有其他屬性(除了eventname和imageurl),則這些其他屬性將出現在您現在添加到列表中的項目中。
您得到的響應是JSON
,您正在嘗試將其解析為XML
。
您想要獲取的list
可以通過簡單地使用
success: function(response) {
var list = (response.results || []).map(function(result) {
return {
eventname: result.eventname,
imageurl : result.imageurl
};
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.