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

标签 jquery ajax json asp.net-mvc-3

我有一个返回 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/

相关文章:

javascript - JQuery如何正确设置 slider 效果

javascript - 从文本文件加载 json

javascript - Ajax 调用 Web 服务 - 方法成功但禁止数据访问

java - 如何使用 Gson 反序列化 XMLGregorianCalender?

python - 为什么protobuf的内存比python中的普通dict+list小?

jquery - 如何仅使用 css3 创建响应式工具提示?

javascript - 系列数据无法触发点击事件 | Highcharts

java - 使用 jQuery 和 Java 代码修改的标签属性不会保存。在ZK

带密码的 AJAX 请求

php - 使用 jQuery/AJAX 从 MySQL DB 获取登录用户列表?