Javascript 使用 jQuery 发送 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6587221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send JSON data with jQuery
提问by Neir0
Why code below sent data as City=Moscow&Age=25
instead of JSON format?
为什么下面的代码发送数据City=Moscow&Age=25
而不是 JSON 格式?
var arr = {City:'Moscow', Age:25};
$.ajax(
{
url: "Ajax.ashx",
type: "POST",
data: arr,
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
}
);
回答by Darin Dimitrov
Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:
因为您既没有指定请求内容类型,也没有指定正确的 JSON 请求。以下是发送 JSON 请求的正确方法:
var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'Ajax.ashx',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
Things to notice:
注意事项:
- Usage of the
JSON.stringify
method to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include json2.js - Specifying the request content type using the
contentType
property in order to indicate to the server the intent of sending a JSON request - The
dataType: 'json'
property is used for the response type you expect from the server. jQuery is intelligent enough to guessit from the serverContent-Type
response header. So if you have a web server which respects more or less the HTTP protocol and responds withContent-Type: application/json
to your request jQuery will automatically parse the response into a javascript object into thesuccess
callback so that you don't need to specify thedataType
property.
- 使用该
JSON.stringify
方法将 javascript 对象转换为 JSON 字符串,该字符串是原生的并内置于现代浏览器中。如果你想支持旧浏览器,你可能需要包含json2.js - 使用
contentType
属性指定请求内容类型,以便向服务器指示发送 JSON 请求的意图 - 该
dataType: 'json'
属性用于您期望从服务器获得的响应类型。jQuery 足够聪明,可以从服务器响应头中猜测它Content-Type
。因此,如果您有一个 Web 服务器,它或多或少地遵守 HTTP 协议并响应Content-Type: application/json
您的请求,jQuery 会自动将响应解析为 javascript 对象到success
回调中,这样您就不需要指定dataType
属性。
Things to be careful about:
需要注意的事项:
- What you call
arr
is not an array. It is a javascript object with properties (City
andAge
). Arrays are denoted with[]
in javascript. For example[{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]
is an array of 2 objects.
- 你所说
arr
的不是数组。它是一个具有属性 (City
和Age
)的 javascript 对象。数组[]
在 javascript中用 表示。例如[{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]
是一个包含 2 个对象的数组。
回答by lonesomeday
Because by default jQuery serializes objects passed as the data
parameter to $.ajax
. It uses $.param
to convert the data to a query string.
因为默认情况下,jQuery 序列化作为data
参数传递给$.ajax
. 它用于$.param
将数据转换为查询字符串。
From the jQuery docs for $.ajax
:
来自 jQuery 文档$.ajax
:
[the
data
argument] is converted to a query string, if not already a string
[
data
参数] 转换为查询字符串,如果还不是字符串
If you want to send JSON, you'll have to encode it yourself:
如果你想发送 JSON,你必须自己编码:
data: JSON.stringify(arr);
Note that JSON.stringify
is only present in modern browsers. For legacy support, look into json2.js
请注意,JSON.stringify
它仅存在于现代浏览器中。对于遗留支持,请查看json2.js
回答by Aram Kocharyan
I wrote a short convenience function for posting JSON.
我写了一个简短的方便函数来发布 JSON。
$.postJSON = function(url, data, success, args) {
args = $.extend({
url: url,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: success
}, args);
return $.ajax(args);
};
$.postJSON('test/url', data, function(result) {
console.log('result', result);
});
回答by Amrit
You need to set the correct content type and stringify your object.
您需要设置正确的内容类型并字符串化您的对象。
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "Ajax.ashx",
type: "POST",
data: JSON.stringify(arr),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert(msg);
}
});
回答by picus
It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.
它被序列化,以便 URI 可以默认读取 POST 请求中的名称值对。您可以尝试将 processData:false 设置为您的参数列表。不确定这是否有帮助。