jQuery 在请求正文中发布有效的 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4159701/
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 posting valid json in request body
提问by brad
So according to the jQuery Ajax docs, it serializes data in the form of a query string when sending requests, but setting processData:false
should allow me to send actual JSON in the body. Unfortunately I'm having a hard time determining first, if this is happening and 2nd what the object looks like that is being sent to the server. All I know is that the server is not parsing what I'm sending.
因此,根据jQuery Ajax 文档,它在发送请求时以查询字符串的形式序列化数据,但设置processData:false
应该允许我在正文中发送实际的 JSON。不幸的是,我很难首先确定,如果发生这种情况,然后确定将对象发送到服务器的样子。我所知道的是服务器没有解析我发送的内容。
When using http clientto post an object literal {someKey:'someData'}
, it works. But when using jQuery with data: {someKey:'someData'}
, it fails. Unfortunately when I analyze the request in Safari, it says the message payload is [object Object]
... great... and in Firefox the post is blank...
使用http 客户端发布对象文字时{someKey:'someData'}
,它可以工作。但是当使用 jQuery with 时data: {someKey:'someData'}
,它失败了。不幸的是,当我在 Safari 中分析请求时,它说消息有效负载是[object Object]
……很棒……而在 Firefox 中,帖子是空白的……
When logging the body content on the Java side it literally gets [object Object]
so how does one send REAL JSON data??
在 Java 端记录正文内容时,它确实得到了[object Object]
如何发送真正的 JSON 数据?
Has anyone had experience with a Java service serializing JSON data in the request body, with the request sent from jQuery?
有没有人有使用 Java 服务序列化请求正文中的 JSON 数据的经验,请求是从 jQuery 发送的?
BTW here is the full $.ajax request:
顺便说一句,这里是完整的 $.ajax 请求:
$.ajax({
contentType: 'application/json',
data: {
"command": "on"
},
dataType: 'json',
success: function(data){
app.log("device control succeeded");
},
error: function(){
app.log("Device control failed");
},
processData: false,
type: 'POST',
url: '/devices/{device_id}/control'
});
回答by Nick Craver
An actual JSON request would look like this:
实际的 JSON 请求如下所示:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
您发送实际 JSON 字符串的位置。对于更通用的解决方案,使用JSON.stringify()
将对象序列化为 JSON,如下所示:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.jswhich will add it in.
要支持没有JSON
对象的旧浏览器,请使用json2.js将其添加进来。
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
目前正在发生的事情是因为你有processData: false
,它基本上是发送这个:({"command":"on"}).toString()
这是[object Object]
......你在你的请求中看到的。