我正在尝试用 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),这些属性将出现在您现在添加到列表中的项目中。
关于Javascript 解析 http 响应时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46514256/