2013-10-01 40 views
0

我有一個JSON對象,我想要發佈到遠程服務器(Rails)。所有將POST參數轉換爲url編碼字符串的嘗試都將失敗的結果作爲'application/json'發送到服務器。 例如:在Rails後端沒有正確接收到具有JSON負載的Crossrider ajax發佈請求

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

+0

閱讀此鏈接。 LMK如果有的話不清楚https://coderwall.com/p/c-mu-a – Renaissance

+1

嘗試先將對象串聯起來。 postData:JSON.stringify({hello:'world',foo:'bar'}) – Bnaya

+0

@Bnaya這解決了我的問題,請添加它作爲解決方案! – hammady

回答

3

您需要首先字符串化的對象。

postData: JSON.stringify({hello: 'world', foo: 'bar'}); 
+0

不能upvote這足夠。 – Albert

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' 
}); 
相關問題