【问题标题】:Loop JSON response after ajax successajax成功后循环JSON响应
【发布时间】:2012-05-02 08:47:25
【问题描述】:

抱歉,这是here 在 SO 中提出的重复问题,但我是新手,所以我想知道该怎么做?

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

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

谁能告诉我该怎么做?

【问题讨论】:

  • @xander-这取决于你获得多少分,这是学习新东西的问题
  • @all-感谢您的回复。

标签: jquery ajax json callback


【解决方案1】:

使用$.each()

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

查看here 了解相关信息。 (编辑:或here - 如果您愿意,这是一个视频教程。)

【讨论】:

    【解决方案2】:

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

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

    这种方法优于 jQuery $.each() 函数,因为它的速度更快。查看此Fiddle 以比较for$.each()

    【讨论】:

      【解决方案3】:

      你可以的;

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-21
        • 2014-02-26
        • 2016-07-04
        • 2010-10-18
        • 2011-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多