[英]JQuery Post sends form data and not JSON
Trying to send json. 试图发送json。 Here's my function: 这是我的功能:
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发送?
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. 注意并非所有浏览器( http://caniuse.com/#feat=json )都支持JSON.stringify,特别是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
Stringify using JSON.stringify(object)
使用JSON.stringify(object)
字符串化
Modify the data
field 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; 你这样做的方式,IMO,jQuery将参数视为字典(键值对),并从中构造百分位编码的字符串; and hence you see that output. 因此你看到了输出。
I have found it easier to send data in default 'application/x-www-form-urlencoded' format with JSON as a field like this: 我发现以默认的'application / x-www-form-urlencoded'格式发送数据更容易,JSON作为这样的字段:
$.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. 只是分享,看看这是否适合你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.