问题描述
有人能否以简单的方式解释如何让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 []:[]
,可能是因为查询sting的限制。
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,然后指定 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或更高版本的浏览器中。如果您需要旧版支持,可以使用。
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而不是查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!