jQuery 循环遍历 AJAX 成功的 JSON 结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/733314/
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:39:22  来源:igfitidea点击:

jQuery loop over JSON result from AJAX Success?

jqueryajaxjson

提问by aherrick

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.

在 jQuery AJAX 成功回调上,我想遍历对象的结果。这是响应在 Firebug 中的外观示例。

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

How can I loop over the results so that I would have access to each of the elements? I have tried something like below but this does not seem to be working.

如何遍历结果以便我可以访问每个元素?我尝试过类似下面的方法,但这似乎不起作用。

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});

回答by cletus

you can remove the outer loop and replace thiswith data.data:

您可以删除外循环并替换thisdata.data

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

你很接近:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

您有一个对象/地图数组,因此外部循环会遍历这些对象/地图。内部循环遍历每个对象元素的属性。

回答by clone45

You can also use the getJSONfunction:

您还可以使用getJSON函数:

    $.getJSON('/your/script.php', function(data) {
        $.each(data, function(index) {
            alert(data[index].TEST1);
            alert(data[index].TEST2);
        });
    });

This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.

这实际上只是对 ifesdjeen 答案的改写,但我认为它可能对人们有所帮助。

回答by 0100110010101

If you use Fire Fox, just open up a console (use F12 key) and try out this:

如果您使用 Fire Fox,只需打开一个控制台(使用 F12 键)并尝试以下操作:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

hope it helps

希望能帮助到你

回答by Dave Hilditch

For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.

对于任何坚持这一点的人,它可能不起作用,因为 ajax 调用将您返回的数据解释为文本 - 即它还不是 JSON 对象。

You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.

您可以通过手动使用 parseJSON 命令或简单地将 dataType: 'json' 属性添加到您的 ajax 调用中,将其转换为 JSON 对象。例如

jQuery.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    data: data, 
    dataType: 'json', // ** ensure you add this line **
    success: function(data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
        });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

回答by Dave Hilditch

Access the json array like you would any other array.

像访问任何其他数组一样访问 json 数组。

for(var i =0;i < itemData.length-1;i++)
{
  var item = itemData[i];
  alert(item.Test1 + item.Test2 + item.Test3);
}

回答by Yovav

This is what I came up with to easily view all data values:

这是我想出的轻松查看所有数据值的方法:

var dataItems = "";
$.each(data, function (index, itemData) {
    dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);

回答by PanwarS87

Try jQuery.mapfunction, works pretty well with maps.

试试jQuery.map函数,与地图配合得很好。

var mapArray = {
  "lastName": "Last Name cannot be null!",
  "email": "Email cannot be null!",
  "firstName": "First Name cannot be null!"
};

$.map(mapArray, function(val, key) {
  alert("Value is :" + val);
  alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by The Dead Guy

if you don't want alert, that is u want html, then do this

如果您不想要警报,那就是您想要 html,然后执行此操作

...
    $.each(data, function(index) {
        $("#pr_result").append(data[index].dbcolumn);
    });
...

NOTE: use "append" not "html" else the last result is what you will be seeing on your html view

注意:使用“append”而不是“html”,否则最后的结果就是您将在 html 视图中看到的结果

then your html code should look like this

那么你的 html 代码应该是这样的

...
<div id="pr_result"></div>
...

You can also style (add class) the div in the jquery before it renders as html

您还可以在将 jquery 中的 div 呈现为 html 之前对其进行样式设置(添加类)

回答by dimitar

I use .map for foreach. For example

我将 .map 用于 foreach。例如

success: function(data) {
  let dataItems = JSON.parse(data)
  dataItems = dataItems.map((item) => {
    return $(`<article>
                <h2>${item.post_title}</h2>
                <p>${item.post_excerpt}</p>
              </article>`)
  })
},

回答by Frederick Eze

If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.

如果您使用如下所示的 JQuery ajax 调用函数的 short 方法,则返回的数据需要解释为 json 对象才能循环。

$.get('url', function(data, statusText, xheader){
 // your code within the success callback
  var data = $.parseJSON(data);
  $.each(data, function(i){
         console.log(data[i]);
      })
})