繁体   English   中英

Javascript错误解析HTTP响应

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM