jQuery 在请求正文中发布有效的 json [英] jQuery posting valid json in request body
问题描述
所以根据jQuery Ajax docs,它以查询的形式序列化数据发送请求时的字符串,但设置 processData:false
应该允许我在正文中发送实际的 JSON.不幸的是,我很难首先确定是否发生了这种情况,其次是将对象发送到服务器的样子.我只知道服务器没有解析我发送的内容.
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.
当使用 http 客户端 发布对象文字 {someKey:'someData'}代码>,它的工作原理.但是当使用带有
data: {someKey:'someData'}
的 jQuery 时,它会失败.不幸的是,当我在 Safari 中分析请求时,它说消息有效负载是 [object Object]
... 太好了......而在 Firefox 中,帖子是空白的......
When using http client to 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...
当在 Java 端记录正文内容时,它实际上得到 [object Object]
那么如何发送真正的 JSON 数据??
When logging the body content on the Java side it literally gets [object Object]
so how does one send REAL JSON data??
有没有人使用 Java 服务序列化请求正文中的 JSON 数据,请求从 jQuery 发送?
Has anyone had experience with a Java service serializing JSON data in the request body, with the request sent from jQuery?
顺便说一句,这里是完整的 $.ajax 请求:
BTW here is the full $.ajax request:
$.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'
});
推荐答案
实际的 JSON 请求如下所示:
An actual JSON request would look like this:
data: '{"command":"on"}',
您发送实际 JSON 字符串的位置.如需更通用的解决方案,请使用 JSON.stringify()
将对象序列化为 JSON,如下所示:
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
要支持没有 JSON
对象的旧浏览器,请使用 json2.js 将其添加进来.
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
当前发生的事情是因为你有 processData: false
,它基本上发送了这个:({"command":"on"}).toString()
这是[object Object]
...您在请求中看到的内容.
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.
这篇关于jQuery 在请求正文中发布有效的 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!