在jQuery AJAX post输出中读取JSON数据

5
我有以下代码,我正在通过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";

以下是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"}}}

这是获取JSON数据的AJAX代码。
$.ajax({
    dataType : 'json',
    url: 'polling.php',
    type: 'post',
    data: 'id=1',
    success: function(data) {
        //read json     

});

我正试图按照编号的顺序读取所有的“msg”并获取每个“Name”和“Said”的值。
然后对“errors”做相同的操作,但我无法正确地检索任何值。

3
笔误...在 'id=1 附近缺少了 ',改为 'id=1' - alwaysLearn
当然,我修改了原始代码以在此处发布。那部分工作正常,但还是谢谢。 - sam fisher
请提供 polling.php 相关的代码,可以吗? - alwaysLearn
2个回答

5
根据您提供的输出:
请尝试使用以下方法:
$(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示例


3

演示 链接

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']);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接