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

可能重复:
如何在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 } } ] 

控制器:

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

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

 $.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); } }); 

还尝试过:

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

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

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

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

见例→


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

 results = JSON.parse(results); 
 $.getJSON("YourControllerHere.XXX",{}, function(data){ $.each(data, function(key, val) { $('#someLocation').append('
  • ' + val.text + '
  • '); //This is just an example. You can do something with each row/ value pair here. }); });

    您应该可以使用此步骤遍历行和值。

    最好,

    Ť

    这是今天另一篇文章的重复 – 你发布了吗? 🙂

    如何在MVC应用程序中返回JSON并循环返回jQuery中的json?

    您的第一个问题是您的JSON中没有result["comments"]字段。 你得到一个数组,我假设是评论本身。 所以你需要迭代它。 就像是

     $.each(result, function(k, v) { console.log(v.user); }); 

    应该工作,我只是在浏览器中尝试过。 以下代码遍历行,然后遍历每行的属性:

     $.each(foo, function(k, row) { $.each(row, function(attr, value) { console.log(attr, value); }) }); 
     for(var key in json) for(var key in (obj = json[key])) { //obj holds the current object in the json array console.log(obj[key]); }