Javascript JQuery Post 发送表单数据而不是 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13956462/
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
JQuery Post sends form data and not JSON
提问by Jason
Trying to send json. Here's my function:
尝试发送json。这是我的功能:
var object = ... ;
$.ajax({
type: 'POST',
url: '<url>',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: object
});
But whenever I check Chrome, it always sends it as query params:
但是每当我检查 Chrome 时,它总是将其作为查询参数发送:
Request Payload:
startDate=Wed+Dec+19+2012+19%3A00%3A00+GMT-0500+(EST)&endDate=Thu+Dec+20+2012+19%3A00%3A00+GMT-0500+(EST)&
How do I get it to send as JSON?
我如何让它作为 JSON 发送?
回答by Stefan
With JSON.stringify(object)
和 JSON.stringify(object)
Sample:
样本:
$.ajax({
type: 'POST',
url: '<url>',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(object)
});
Note JSON.stringify is not supported in all browsers (http://caniuse.com/#feat=json), in particular browsers IE7 and lower.
注意 JSON.stringify 并非在所有浏览器 ( http://caniuse.com/#feat=json)中都受支持,尤其是 IE7 及更低版本的浏览器。
If you need to support this browsers too you can use this Javascript library: https://github.com/douglascrockford/JSON-js
如果你也需要支持这个浏览器,你可以使用这个 Javascript 库:https: //github.com/douglascrockford/JSON-js
回答by UltraInstinct
Stringifyusing JSON.stringify(object)
字符串化使用JSON.stringify(object)
Modify the datafield to:
将data字段修改为:
...
data: JSON.stringify(object),
...
The way you are doing it, IMO, jQuery sees the parameter as a dictionary (key-value pairs), and constructs a percentile-encoded string from that; and hence you see that output.
你这样做的方式,IMO,jQuery 将参数视为字典(键值对),并从中构造一个百分位编码的字符串;因此你会看到那个输出。
回答by closure
I have found it easier to send data in default 'application/x-www-form-urlencoded' format with JSON as a field like this:
我发现使用 JSON 作为字段以默认的“application/x-www-form-urlencoded”格式发送数据更容易,如下所示:
$.ajax({
type: 'POST',
url: '<url>',
dataType: 'json',
data: {json:JSON.stringify(object)}
});
On server use the regular method to receive field called json.
在服务器上使用常规方法接收名为json.
Just shared to see if this is valid for you.
只是分享,看看这对你是否有效。

