javascript 在 jQuery AJAX 后输出中读取 JSON 数据

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

Reading JSON data in jQuery AJAX post output

javascriptjqueryajaxarraysjson

提问by sam fisher

I have the code below which i am passing through json to jquery.

我有下面的代码,我将通过 json 传递给 jquery。

$string['msg']['1']['Name'] = "John Doe";
$string['msg']['1']['Said'] = "Hello there";

$string['msg']['2']['Name'] = "Jane King";
$string['msg']['2']['Said'] = "Hello there";

$string['errors']['1']['Person'] = "Jane King";
$string['errors']['1']['type'] = "Wrong Screwdriver";


$string['errors']['2']['Person'] = "John Doe";
$string['errors']['2']['type'] = "Wrong Spanner";

The JSON output is below:

JSON 输出如下:

{"msg":{"1":{"Name":"John Doe","Said":"Hello there"},"2":{"Name":"Jane King","Said":"Hello there"}},"errors":{"1":{"Person":"Jane King","type":"Wrong Screwdriver"},"2":{"Person":"John Doe","type":"Wrong Spanner"}}}

This is the ajax code that is retreiving the json.

这是检索 json 的 ajax 代码。

$.ajax({
    dataType : 'json',
    url: 'polling.php',
    type: 'post',
    data: 'id=1',
    success: function(data) {
        //read json     

});

I am trying to read all 'msg' in order of number.. 1, 2.. and get 'Name' and 'Said' values for each.

我正在尝试按数字顺序读取所有“味精”.. 1、2.. 并为每个获取“名称”和“说”值。

Then do the same for 'errors'

然后对“错误”执行相同的操作

but i cant correctly retrieve any values

但我无法正确检索任何值

回答by Satpal

As per your given output:

根据您给定的输出:

Try this:

试试这个:

$(function(){

    var  data = {"msg":{"1":{"Name":"John Doe","Said":"Hello there"},"2":{"Name":"Jane King","Said":"Hello there"}},"errors":{"1":{"Person":"Jane King","type":"Wrong Screwdriver"},"2":{"Person":"John Doe","type":"Wrong Spanner"}}};

    $.each(data.msg, function(index, value) {
      alert(index + ': ' + value.Name);
    });

});

JSFiddle Example

JSFiddle 示例

回答by Jayendra

Demo Link

演示链接

var data = {"msg":{"1":{"Name":"John Doe","Said":"Hello there"},"2":{"Name":"Jane King","Said":"Hello there"}},"errors":{"1":{"Person":"Jane King","type":"Wrong Screwdriver"},"2":{"Person":"John Doe","type":"Wrong Spanner"}}};


$.each(data['msg'], function(key, element){
    console.log(key+' : '+element['Name']);
});

$.each(data['errors'], function(key, element){
    console.log(key+' : '+element['Person']);
});