如何使用 $.ajax 发送 JSON 而不是查询字符串? [英] How to send JSON instead of a query string with $.ajax?
问题描述
有人可以简单地解释一下如何让 jQuery 发送实际的 JSON 而不是查询字符串吗?
Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
这实际上会将您精心准备的 JSON 转换为查询字符串.一件烦人的事情是,您对象中的任何 array: []
都将被转换为 array[]: []
,这可能是因为查询字符串的限制.
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: []
in your object will be converted to array[]: []
, probably because of limitations of the query sting.
推荐答案
您需要使用 JSON.stringify
首先将您的对象序列化为 JSON,然后指定 contentType
以便您的服务器理解它是 JSON.这应该可以解决问题:
You need to use JSON.stringify
to first serialize your object to JSON, and then specify the contentType
so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
请注意,JSON
对象在支持 JavaScript 1.7/ECMAScript 5 或更高版本的浏览器中本机可用.如果您需要旧版支持,您可以使用 json2.
Note that the JSON
object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
这篇关于如何使用 $.ajax 发送 JSON 而不是查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!