2012-04-20 133 views
5

对不起,这是从here复制的,但是我是新手,所以我想知道该怎么做?ajax成功后的循环JSON响应

这是我的Ajax调用:

$("#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]); 
         } 
       }); 
    }); 

独立,我能得到响应,但我需要循环它们。

任何人都可以说我该怎么做?

+0

@ xander-dosent取决于你获得多少分是学习新东西的问题 – coder 2012-04-20 18:48:20

+0

@全部感谢您的回复。 – coder 2012-04-20 18:51:36

回答

4

你可以做;

for (var i=0; i<response.d.length; i++) { 
alert(response.d[i]); 
} 
+0

请解释代码。 – Rehan 2017-04-10 18:01:52

10

使用$.each()

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

here学习一下吧。 (编辑:或者here - 这是一个视频教程,如果你喜欢的。)

+0

谢谢man.i只是在寻找这个解决方案。 – 2013-03-04 10:56:12

6

如果response.d是一个数组,你可以把它放在一个for循环,像这样:

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

这种方法优于jQuery $.each()功能由于其更快的性质。查看Fiddle,以便比较for$.each()