1

我有一些 JSON,例如:

response = [
  {"FIRSTNAME":"Richard","ACCOUNT":5555,"ID":"5056","LASTNAME":"Harris"},  
  {"FIRSTNAME":"Gary","ACCOUNT":4444,"ID":"DFC7","LASTNAME":"Coles"},
  {"FIRSTNAME":"Jeff","CORPORATEACCOUNT":3333,"ID":"7F31","LASTNAME":"Hopper"},
  {"FIRSTNAME":"Jack","ACCOUNT":2222,"ID":"E051","LASTNAME":"Canrell"},
  {"FIRSTNAME":"Tim","ACCOUNT":1111,"ID":"5056","LASTNAME":"Johns"}
]

我需要遍历它并为每个用户显示一行,而我的 jQuery 不起作用。我究竟做错了什么?

$.ajax({
    type: "POST",
    url: "/my-controller/my-method?format=json",
    data: {id: id},
    dataType: "json",
    success: function(response) {
        var resultHtml = '';
        $.each(response, function(i, response) {
            $.each(response, function(property, value) {
            resultHtml += value + '\n';
        });
        });

        alert(resultHtml);
    }
});

所以这呼应了:

Richard
5555
5056
Harris
Gary
4444
DFC7
Coles
etc.
etc.
etc.

JSON 正在从控制器返回,但我如何循环并获取它?

Richard harris 5555 5056
Gary Coles 4444 DFC7
Jeff Hopper 3333 7F31
Jack Canrell 2222 E051
Tim Johns 1111 5060
4

3 回答 3

8

你不需要$.each第二次。您有一个对象,只需使用您想要的字段。

$.each(response, function(i, value) {
    resultHtml += value.FIRSTNAME + value.LASTNAME + value.ACCOUNT + value.ID + '\n';
});
于 2012-11-19T18:50:43.177 回答
0

你需要先解析 JSON,试试 JSON.parse(response); 让它创建一个可以迭代的对象。

于 2012-11-19T18:50:36.100 回答
0
$.ajax({
    type: "POST",
    url: "/my-controller/my-method?format=json",
    data: {id: id},
    dataType: "json",
    success: function(response) {
        var resultHtml = '';
        $.each(response, function(i, row) {
            resultHTML += row.FIRSTNAME + " " + row.LASTNAME + " " + row.ACCOUNT + " " + row.ID + "\n";
        });
        alert(resultHtml);
    }
});
于 2012-11-19T18:52:43.313 回答