如何循环jquery返回的JSON数据?

khe*_*eya 7 javascript jquery json asp.net-mvc-3

可能重复:
如何在MVC应用程序中返回JSON并循环返回jQuery中的json?

这是我的MVC控制器返回的数据,我在成功回调中得到了这个:

[{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "First comment!!", "dt" : { "$date" : 1304966277978 } }, 
 { "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Second comment!!", "dt" : { "$date" : 1304966347677 } }, 
 { "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Third comment!!", "dt" : { "$date" : 1304966493240 } }
]
Run Code Online (Sandbox Code Playgroud)

控制器:

[HttpGet]
public JsonResult GetComments(params...)
{
   return Json(new { comments = GetFromDB().ToJson() }, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

问题: 我尝试了几种循环行的方法.但似乎无限循环.

$.ajax(
        {
            type: "GET",
            url: "/comment/GetComments",
            dataType: "json",
            data: "app=" + app + "&eid=" + eid + "&pg=" + pg + "&pgs=" + pgs,
            success: function (result) {
                $.each(result[comments], function () {
                   $.each(this, function (k, v) {
                        alert('this a column or attribute');
                   });
                   alert('end of row');
               });
            },
            error: function (req, status, error) {
                alert('Error=' + error + ' & Status=' + status);
            }
        });   
Run Code Online (Sandbox Code Playgroud)

还尝试过:

$.each(result["comments"], function (key, value) {
   alert('comment found');
});
Run Code Online (Sandbox Code Playgroud)

如何循环行并访问每个属性的值?

mVC*_*Chr 4

你可以只使用一个简单的for循环:

for (var i = 0, len = results.length; i < len; i++) {
    // do something with results[i].text
}
Run Code Online (Sandbox Code Playgroud)

参见示例 →


编辑:如果您需要首先将 JSON 字符串转换为 Javascript 对象,那么在循环之前您应该:

results = JSON.parse(results);
Run Code Online (Sandbox Code Playgroud)