Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop JSON data returned by jquery? [duplicate]

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?

like image 858
kheya Avatar asked May 10 '11 18:05

kheya


1 Answers

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);
like image 172
mVChr Avatar answered Sep 20 '22 14:09

mVChr