[英]Crossrider ajax post requests having JSON payload are not received correctly in Rails backend
我有一個要發布到遠程服務器(Rails)的JSON對象。 將POST參數轉換為url編碼的字符串后,所有嘗試以“ application / json”形式將其發送到服務器都會失敗。 例如:
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'
});
當服務器從格式錯誤的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'
...
我還應該怎么做才能將JSON對象發送到我的Rails后端?
您需要先對對象進行字符串化。
postData: JSON.stringify({hello: 'world', foo: 'bar'});
使用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.