Possible Duplicate:
How do I return JSON and loop through the returned json in jQuery in MVC app?
This is my data returned by MVC controller and I get this in my success callback:
[{ "_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 } }
]
Controller:
[HttpGet]
public JsonResult GetComments(params...)
{
return Json(new { comments = GetFromDB().ToJson() }, JsonRequestBehavior.AllowGet);
}
Problem: I tried several ways to loop the rows. But all seems infinite loop.
$.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);
}
});
Also tried:
$.each(result["comments"], function (key, value) {
alert('comment found');
});
How can I loop the rows & access each attribute's value?
You could just use a simple for
loop:
for (var i = 0, len = results.length; i < len; i++) {
// do something with results[i].text
}
See example →
EDIT: If you need to first convert a JSON string to a Javascript object then before the loop you should:
results = JSON.parse(results);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With