简体   繁体   中英

how to iterate each array element in response in $.ajax

First thing, the simple response which I get back from $.ajax is this: http://pastebin.com/eEE72ySk

I am using this code:

$.ajax({
    url: "/api/Flight/SearchFlight",
    type: "Post",
    data: $('form').serialize() + '&' + $.param({
        'TokenId': $("#pageInitCounter").val()
    }, true),
    success: function(data) {
        var result = JSON.parse(data);
        $('#responsestatus').text(result.Response.ResponseStatus);
    });

I was trying this code:

$.each(result.Response.Results[0][0].AirlineRemark, function (i, item) {
    $("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
});

When I use the above code, then error is:

Uncaught TypeError: Cannot use 'in' operator to search for '5' in IndiGo

When I tried this code without the forEach loop :

 $("#divResult1").text(result.Response.Results[0][0].AirlineRemark);

I get no error but the output is only the first one. Indigo is showing however in response there are 20 arrays in Results. I have shown only two arrays in result in the link provided above.

Please someone tell me how to iterate each and every item in results array.

AirlineRemark is not an Array, so looping through that one is not possible. So loop through the array of arrays, and find the property within each loop

   $.each(result.Response.Results[0], function (i, item) {
      $("#divResult1").append('<p>' + item.AirlineRemark + '</p>');
    });

You're trying to iterate a non-array there. If, result is based on your JSON that you provided. This is one way you can iterate it,

// Each items in result.Response.Results
$.each(result.Response.Results, function(i, items) {
  // Get the AirlineRemark at the item at 0 index.
  var airlineRemark = items[0].AirlineRemark;

  // Append it to #divResult1
  $("#divResult1").append('<p>' + airlineRemark + '</p>');
});

Beware that on sample above, items is an array. And it will only get the first item.

You can try this

   $.each(result.Response.Results, function () {
      $("#divResult1").append('<p>'+this[0].AirlineRemark+'</p>');
    });

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