【问题标题】:AJAX data parse to Controller and return backAJAX 数据解析到 Controller 并返回
【发布时间】:2017-05-11 09:30:37
【问题描述】:

这是对控制器的 AJAX 调用:

$.ajax({
    type: "GET",
    url: '@Url.Action("getChat", "Chat")',
    success: function (data) {
        alert(data);
        $("#data").html(data);
    },
    error:{                  
    }
});

在控制器代码中,我有一个返回多行的数据库查询。

我想将该变量返回给 JSON,并在 AJAX 中分别打印每一行,并在 HTML 中写入该数据。

这是我的控制器代码

public ActionResult getChat()
{
    var p = (from v in DB.chats where v.chatuserID == id select new { v.status, v.message }).ToList();
    return Content(p.ToString());
}

查询正在返回数据。我附上了显示变量内容的图像。

【问题讨论】:

  • 需要定义数据的返回类型,在ajax中可以使用dataType:'json'从控制器json返回..
  • 返回 json(p , json----------allow)

标签: asp.net ajax


【解决方案1】:
public JsonResult getChat()
{
   var p = (from v in DB.chats 
            where v.chatuserID == id select new { v.status, 
            v.message 
            }).ToList();

    return json(p,JsonRequestBehavior.AllowGet);
}

现在您可以在 ajax 成功回调函数中循环遍历列表:这里有东西。

$.ajax({
             type: "GET",
             url: '@Url.Action("getChat", "Chat")',
             success: function (data) {
             $.each(data,function(){
             console.log("Status "+ data.status +" "+"Message"+ data.message);
             });
             },
             error:{                  
             }
   });

【讨论】:

  • 状态未定义:消息未定义
  • 你得到数据变量的响应了吗??
  • 是的,它进入了成功功能,我已经写了它在控制台中显示的内容。
  • $.each(data,function(key,value){ console.log("状态 "+ value["status"] +" "+"Message"+ value["message"]) ; });
猜你喜欢
  • 2011-01-24
  • 2019-11-10
  • 1970-01-01
  • 2023-04-05
  • 2011-09-30
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 2019-02-27
相关资源
最近更新 更多