我有一个返回 JSON 的 MVC Controller 。 我想使用 jQuery 读取/获取 JSON 并循环遍历 json 项/行。
基本上我正在阅读一堆评论,然后逐条显示评论。
有人有代码示例吗?
我正确地获取了 json。请参阅下面返回的数据。
$.ajax(
{
type: "GET",
url: "/comment/GetComments",
dataType: "json",
data: "blog_id=100&page_size=5&page_no=1",
success: function (result) {
//loop the data.. how do I loop json?
},
error: function (req, status, error) {
alert('Error getting comments');
}
});
My controller:
[HttpGet]
public ActionResult GetComments(string blog_id, int page_size, int page_no)
{
try
{
List<Comment> comments = ReadCommentsFromDB();
if(comments .Count > 0)
return Json(new { comments = cmts.ToJson() }, JsonRequestBehavior.AllowGet);
else
return Json(new { comments = "none" },, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { comments = ex.ToString() }, JsonRequestBehavior.AllowGet);
}
}
谢谢
编辑:
如何循环 Controller 返回的这些 json? 我需要循环 3 次,然后对于每一行,我需要访问所有键和值 在那一行。
[{ "_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 } }
]
最佳答案
success: function(result) {
$.each(result["comments"], function(key, value) {
// loop
});
}
你的结果应该是一个 json 对象
{
"comments": ...
}
至于尝试失败:
type: "GET",
url: "/comment/GetComments?blog_id=100&page_size=5&page_no=1",
dataType: "json",
//data: "blog_id=100&page_size=5&page_no=1",
关于jquery - 如何在 MVC 应用程序中返回 JSON 并循环遍历 jQuery 中返回的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5953761/