jQuery ajax成功后循环JSON响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10251772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:01:45  来源:igfitidea点击:

Loop JSON response after ajax success

jqueryajaxjsoncallback

提问by coder

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

对不起,这是从这里问到的重复,但我是新手,所以我想知道怎么做?

This is my ajax call:

这是我的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]);
                      }
                });
  });

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

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

Can anyone say me how do I do this?

谁能告诉我我该怎么做?

回答by Jonny Burger

Use $.each().

使用$.each().

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

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

这里了解它。(编辑:或者在这里- 如果您愿意,这是一个视频教程。)

回答by jasonmerino

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

ifresponse.d是一个数组,您可以将它放在 for 循环中,如下所示:

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 Fiddlefor a comparison of forvs $.each().

$.each()由于其速度更快,此方法优于 jQuery函数。查看这个Fiddle比较forvs $.each().

回答by keune

You could do;

你可以这样做;

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