简体   繁体   中英

Javascript error parsing http response

I am trying to parse the response from the www.skiddle.com API in Javascript:

$.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);
        });

The response actually has a results property with one element in the array:

{error: 0, totalcount: "1", pagecount: 1, results: Array(1)}

but I can't seem to parse it correctly, $(response).find("results") returns nothing.

If you are sure that there will be a result array property in your response, you may simply use response.results which gives you the array.

success: function(response) {

  $.each(response.results,function(indx,item){
       console.log(item);
       var obj = {  
                    eventname: item.eventname,
                    imageurl : item.imageurl
                 };
      list.push(obj);
  });

}

Assuming list is an array defined earlier.

Also if you are sure there will be only one item in the array, you do not need a loop, you can access it via 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);
  }
}

I also noticed that the your new object has the same property names as the object you are iterating. In that case, you can simply add the same object

 list.push(response.results[0]);

Of course this will add the first item as it is , which means if that has additional properties (other than eventname and imageurl) those will be present in the item you are adding to list now..

The response you are getting is a JSON , you are trying to parse it as XML .

The list you are trying to get can be obtained by simply using

success: function(response) {
    var list = (response.results || []).map(function(result) {
        return {  
            eventname: result.eventname,
            imageurl : result.imageurl
        };
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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