0

我有一个要发布到远程服务器(Rails)的 JSON 对象。所有将其作为 'application/json' 发送到服务器的尝试都失败,其中 POST 参数在某处转换为 url 编码的字符串。例如:

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'
});

返回 HTTP 500,服务器抱怨格式错误的 JSON 对象:

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 后端?

4

2 回答 2

3

您需要先对对象进行字符串化。

postData: JSON.stringify({hello: 'world', foo: 'bar'});
于 2013-10-14T13:38:22.697 回答
1

使用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'
});
于 2013-10-12T09:43:46.797 回答