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

2023-12-09

我有一个返回 JSON 的 MVC 控制器。 我想使用 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);
        }
    }

Thanks

EDIT:

如何循环控制器返回的这些 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",
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MVC 应用程序中返回 JSON 并循环遍历 jQuery 中返回的 json? 的相关文章

随机推荐