[英]Crossrider ajax post requests having JSON payload are not received correctly in Rails backend
I have a JSON object that I want to post to a remote server (Rails). 我有一个要发布到远程服务器(Rails)的JSON对象。 All attempts to send it to the server as 'application/json' fail where POST parameters are converted somewhere to url-encoded string. 将POST参数转换为url编码的字符串后,所有尝试以“ application / json”形式将其发送到服务器都会失败。 For example: 例如:
appAPI.request.post({
url: "http://mybackend",
postData: {hello: 'world', foo: 'bar'},
onSuccess: function(response) {
console.log("postback succeeded with response: " + response)
},
onFailure: function(httpCode) {
console.log("postback failure: " + httpCode)
},
contentType: 'application/json'
});
Returns HTTP 500 with the server complaining from a malformed JSON object: 当服务器从格式错误的JSON对象抱怨时返回HTTP 500:
Error occurred while parsing request parameters.
Contents:
MultiJson::LoadError (784: unexpected token at 'hello=world&foo=bar'):
/Users/hammady/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/json/common.rb:148:in `parse'
...
What else should I do to send the JSON object to my Rails backend? 我还应该怎么做才能将JSON对象发送到我的Rails后端?
您需要先对对象进行字符串化。
postData: JSON.stringify({hello: 'world', foo: 'bar'});
use JSON.stringify to stringify the posted data 使用JSON.stringify对发布的数据进行字符串化
appAPI.request.post({
url: "http://mybackend",
postData: JSON.stringify({hello: 'world', foo: 'bar'}),
onSuccess: function(response) {
console.log("postback succeeded with response: " + response)
},
onFailure: function(httpCode) {
console.log("postback failure: " + httpCode)
},
contentType: 'application/json'
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.