Nate Pet
Nate Pet

Reputation: 46282

ajax call return list

I am making an ajax call

     $.ajax({
           url: urpath,
           type: 'POST',
           dataType: 'json',
           data: JSON.stringify(json),
           contentType: 'application/json; charset=utf-8',
           success: function (data) {
                        alert(data);
                    },
           error: error
     });

The returning data is a list which has 2 columns. How do I iterate through the list and show the data. When I do alert(data) it just says object object?

Upvotes: 1

Views: 26354

Answers (2)

Sarfraz
Sarfraz

Reputation: 382826

Use for-in loop:

for (var i in data){
  // data[i].something, etc
}

So here is how your code should be:

$.ajax({    
   url: urpath,
   type: 'POST',
   dataType: 'json',
   data: JSON.stringify(json),
   contentType: 'application/json; charset=utf-8',
   success: function (data) {
     for (var i in data){
      // data[i].something, etc
     }
   },
   error: error // assuming error is function
});

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1039248

If the JSON is indeed a list containing objects with 2 properties like this:

[{"prop1":"value1", "prop2":"value2"}, {"prop1":"value3", "prop2":"value4"}]

You could loop through them using the $.each method and inside the callback the this variable will point to each element in the list and you can access individual properties:

$.each(data, function() {
    alert('prop1=' + this.prop1 + ', prop2=' + this.prop2);
});

Upvotes: 2

Related Questions