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'.. 1、2.. 并获取每个的 'Name' 和 'Said' 值。

然后对“错误”做同样的事情

但我无法正确检索任何值

4

2 回答 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 示例

于 2013-05-16T05:56:26.563 回答
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']);
});
于 2013-05-16T05:57:58.110 回答