如何在jQuery中通过Request Body提交JSON数据?

时间:2014-01-18 07:18:25

标签: javascript jquery ajax json

我不是jQuery的专家,认为我更新鲜。这是我的代码,它不负责Request Body提交的jQuery JSON数据。

<!doctype html>
<html lang="en">
<head>
    <title>jQuery Data submitted by JSON Body Request</title>
    <script type="text/javascript" src="jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $.ajax({
        url : "/",
        type: "POST",
        data: [
            {id: 1, name: "Shahed"}, 
            {id: 2, name: "Hossain"}
        ],
        contentType: "application/json; charset=utf-8",
        dataType   : "json",
        success    : function(){
            console.log("Pure jQuery Pure JS object");
        }
    });

    </script>
</head>
<body>
    <p>
        Example of submission JS Object by JSON Body Request<br/>
        Its could submitted mass amount of data by Message body<br/>
        It's secured and faster than any data submission .
    </p>
</body>
</html>

Post Source出现了:

Shahed=undefined&Hossain=undefined

但是期望的Post Source是:

[{"id":1,"name":"Shahed"},{"id":2,"name":"Hossain"}]

如何为每个请求主体获取所需的帖子来源?

1 个答案:

答案 0 :(得分:17)

这是您想要的输出的正确代码。

$.ajax({
        url : "/",
        type: "POST",
        data: JSON.stringify([
            {id: 1, name: "Shahed"}, 
            {id: 2, name: "Hossain"}
        ]),
        contentType: "application/json; charset=utf-8",
        dataType   : "json",
        success    : function(){
            console.log("Pure jQuery Pure JS object");
        }
    });

您必须将JS对象转换为字符串,JSON.stringify(JSObject)是负责此操作的方法。