5

Sorry this is a duplicate from here asked in SO but I'm new to this so I would like to know how to do it?

This is my ajax call:

  $("#btnprocess").click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetFilenames",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response.d[0]);
                        alert(response.d[1]);
                      }
                });
  });

Individually I'm able to get the response but I need to loop them.

Can anyone say me how do I do this?

Community
  • 1
  • 1
coder
  • 13,002
  • 31
  • 112
  • 214

3 Answers3

12

Use $.each().

$.each(response.d, function(key, value) {
    //For example
    console.log(key + value)
})

Look here to learn about it. (EDIT: Or here - it's a video tutorial if you prefer that.)

Michael Coxon
  • 5,311
  • 1
  • 24
  • 51
Jonny Burger
  • 922
  • 4
  • 11
7

if response.d is an array you could place it in a for loop like so:

for ( var i = 0; i < response.d.length; i++ ) {
    // do action here
}

This method is preferred over the jQuery $.each() function due to its speedier nature. Check out this Fiddle for a comparison of for vs $.each().

jasonmerino
  • 3,220
  • 1
  • 21
  • 38
6

You could do;

for (var i=0; i<response.d.length; i++) {
 alert(response.d[i]);
}
keune
  • 5,779
  • 4
  • 34
  • 50