繁体   English   中英

Rails后端未正确接收具有JSON有效负载的Crossrider Ajax发布请求

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM