循环遍历JSON对象列表

Nic*_*ick 62 javascript jquery json web-services

我从Web服务返回List <>作为JSON对象列表.我试图使用for循环迭代列表并从属性中获取值.这是返回JSON的示例:

{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
 "EmployeeName":"Janet Leverling",
 "EmployeeTitle":"Sales Representative",
 "RequiredDate":"\/Date(839224800000)\/",
 "OrderedProducts":null}]}
Run Code Online (Sandbox Code Playgroud)

所以我试图用这样的东西提取内容:

function PrintResults(result) {

for (var i = 0; i < result.length; i++) { 
    alert(result.employeename);
}
Run Code Online (Sandbox Code Playgroud)

该怎么做?

Bur*_*gan 68

小心,d是清单.

for (var i = 0; i < result.d.length; i++) { 
    alert(result.d[i].employeename);
}
Run Code Online (Sandbox Code Playgroud)


小智 53

今天有同样的问题,你的主题帮助了我,所以这里解决了;)

 alert(result.d[0].EmployeeTitle);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这也是我得出的结论.这是一篇很好的帖子,详细解决了这个问题.http://elegantcode.com/2009/05/04/jquery-ajax-with-class-arrays/希望这有助于其他人. (5认同)
  • 上面评论中的链接是不死生物 (2认同)

Cᴏʀ*_*ᴏʀʏ 19

很近!试试这个:

for (var prop in result) {
    if (result.hasOwnProperty(prop)) {
        alert(result[prop]);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

如果您的结果确实是一个对象的数组,那么您可能必须这样做:

for (var prop in result[0]) {
    if (result[0].hasOwnProperty(prop)) {
        alert(result[0][prop]);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想循环遍历数组中的每个结果,请尝试:

for (var i = 0; i < results.length; i++) {
    for (var prop in result[i]) {
        if (result[i].hasOwnProperty(prop)) {
            alert(result[i][prop]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 16

这里是:

success: 
    function(data) {
        $.each(data, function(i, item){
            alert("Mine is " + i + "|" + item.title + "|" + item.key);
        });
    }
Run Code Online (Sandbox Code Playgroud)

示例JSON文本:

{"title": "camp crowhouse", 
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}
Run Code Online (Sandbox Code Playgroud)


Kyl*_*ris 9

既然你正在使用jQuery,你也可以使用每个方法......而且,似乎所有东西都是这个JS对象[Notation]中属性'd'的值.

$.each(result.d,function(i) {
    // In case there are several values in the array 'd'
    $.each(this,function(j) {
        // Apparently doesn't work...
        alert(this.EmployeeName);
        // What about this?
        alert(result.d[i][j]['EmployeeName']);
        // Or this?
        alert(result.d[i][j].EmployeeName);
    });
});
Run Code Online (Sandbox Code Playgroud)

这应该工作.如果没有,那么也许你可以给我们一个更长的JSON例子.

编辑:如果这些东西都不起作用,那么我开始认为你的JSON的语法可能有问题.


小智 7

var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
    alert(d[i].EmployeeName);
}
Run Code Online (Sandbox Code Playgroud)