Jquery Ajax 提交json数据

在MVC控制器(这里是TestController)下有一个CreateOrder的Action方法

[HttpPost]
public ActionResult CreateOrder(List<Person> model)
{
    return View();
}

其中Person类如下:

public class Person
{
    public string Name { get; set; }

    public string IDCard { get; set; }
}

这里类似购买火车票的一个场景,购买票的时候要求提供所有乘车人的信息(姓名、身份证号码)

前台视图的代码如下:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>CreateOrder</title>
</head>
<body>
    <input type="button" value="提交订单" id="btnSubmit" />
    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript">
        var persons = [{ Name: "张三", IDCard:"44111111"},{Name:"姣婆莲",IDCard:"33222222"}];
        $(function () {
            $("#btnSubmit").click(function () {
                $.ajax({
                    url: '@Url.Action("CreateOrder","Test")',
                    type: 'POST',
                    data: persons,
                    success: function (responseText) {

                    }
                });
            });
        });
    </script>
</body>
</html>
View Code

点击按钮时发起Ajax请求,提交json数据,json数据包含了两位乘客信息(这里只是演示数据的提交,不讨论身份证号码的合法性)

当点击按钮时,在开发人员工具中看到发起了Ajax请求,但是表单数据不是json数据

 

 

而在调试中也可以监视到参数model是null

 

从开发人员工具中可以看到,请求头是Content-Type:application/x-www-form-urlencoded; charset=UTF-8 ,而实际应该是Content-Type:application/json; charset=UTF-8

于是对视图作修改:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>CreateOrder</title>
</head>
<body>
    <input type="button" value="提交订单" id="btnSubmit" />
    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript">
        var persons = [{ Name: "张三", IDCard:"44111111"},{Name:"姣婆莲",IDCard:"33222222"}];
        $(function () {
            $("#btnSubmit").click(function () {
                $.ajax({
                    url: '@Url.Action("CreateOrder","Test")',
                    type: 'POST',
                    data:JSON.stringify(persons),
                    contentType:"application/json;charset=utf-8",
                    success: function (responseText) {

                    }
                });
            });
        });
    </script>
</body>
</html>
View Code

修改视图后,刷新页面,点击按钮再次发起请求

 

 

成功。

注意:jquery ajax请求中设置了contentType之后,需要将参数data设置为json字符串,使用JSON.stringify() ,否则提交时会提示如下:

 

posted @ 2017-08-25 23:15  Jichan·Jong  阅读(8970)  评论(0编辑  收藏  举报