2011-05-10 18 views
7

可能重複:
How do I return JSON and loop through the returned json in jQuery in MVC app?如何循環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'); 
}); 

我怎麼能環行&訪問的每個屬性的值?

+0

那麼你的Ajax調用的樣子? – 2011-05-10 18:28:51

+0

請編輯您的帖子,而不是粘貼代碼在 – mcgrailm 2011-05-10 18:31:52

+0

您今天發佈基本上相同的東西在:http://stackoverflow.com/questions/5953761/how-do-i-return-json-and-loop-through-the -json-in-jquery-in-mvc-app/5954010#5954010 – 2011-05-10 18:45:57

回答

4

你可以只用一個簡單的for循環:

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

See example →


編輯:如果您需要首先一個JSON字符串轉換爲JavaScript對象則環路你應該之前:

results = JSON.parse(results); 
+0

它在jsfiddle中工作,但不在我的瀏覽器上。 alert('len ='+ results.length)打印出json響應中的總字符數,而不是響應中的項數。這是原因嗎?它將json視爲純文本? – kheya 2011-05-10 19:02:10

+0

JSON是一種文本格式:http://www.json.org/ – Tamler 2011-05-10 19:10:11

+0

我更新了我的答案。 – mVChr 2011-05-10 19:10:54

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

您應該可以通過這些步驟和值來逐步完成。

最佳,

牛逼

1

你的第一個問題是,在你的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); }) }); 
1
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]); 
     }