2009-11-17 34 views
54

我試圖通過Ajax將一些JSON格式的數據與jQuery加到服務器上。我的代碼如下所示:jQuery - 如何通過Ajax放置JSON?

$.ajax({ 
    type: "PUT", 
    url: myURL, 
    contentType: "application/json", 
    data: {"data": "mydata"} 
}); 

但在服務器端,我得到的不是預期的一個JSON字符串data=mydata,。 Firebug告訴我一樣。

錯誤在哪裏?

+0

? – 2009-11-17 14:37:26

+0

我使用期望JSON的Couchdb。 – 2009-11-17 14:43:18

+6

AJAX PUT *可在所有主流瀏覽器中使用。 HTTP PUT不是。所以在這種情況下,使用PUT是很好的(推薦,甚至是)。 – 2013-07-02 19:39:37

回答

46

我認爲數據需要是一個字符串。對象被轉換爲查詢字符串,這就是你在這裏看到的。

您可以使用JSON.stringify(obj)方法將您的對象轉換爲字符串。 JSON對象的代碼可從:https://github.com/douglascrockford/JSON-js/blob/master/json2.js獲取。

或者,只是傳遞您用來創建對象的代碼作爲文字字符串,但我想這只是一個示例,您需要編碼您已創建的某個對象。

+1

這是@Juri應該去的方式,如果他想在服務器上使用JSON。我一直使用json2.js庫,並且效果很好。 – 2009-11-17 14:41:07

+3

會很好,如果jQuery將字符串數據,就像它與POST一樣。 – neoneye 2011-12-04 23:06:30

+1

更新後的鏈接:https://github.com/douglascrockford/JSON-js/blob/master/json2.js – Ben 2012-05-08 05:17:55

30

如果您始終必須在您的應用程序中發送JSON,那麼您可以在init中的某處執行此操作,然後使用默認的$.ajax調用,並且它將始終序列化爲JSON字符串而不是Ajax默認值請求參數。

這裏我用上面提到的JSON對象:什麼是你在服務器端使用

$.ajaxSetup({ 
    contentType : 'application/json', 
    processData : false 
}); 
$.ajaxPrefilter(function(options, originalOptions, jqXHR) { 
    if (options.data){ 
     options.data=JSON.stringify(options.data); 
    } 
}); 
1
//url: this is a reference to the XML, where you need to define the mapping. 
//<entry key="/getEmpDetails/transEfileGenerate.app"> 
//<bean class="com.adp.ems.framework.spring.MappingItem" p:delegate-ref="efilePageDelegate" 
//p:action="passJSONObjectAndGetWebServiceOutput" /> 

//str1 is the input JSON that you need to pass... Ajax will automatically take care to get the response. 
//</entry> 

var kw = { 
    url : "getEmpDetails/transEfileGenerate.app", 
    timeout : 30000, 
    handleAs : "json", 
    sync: false, 
    putData : str1, 
    headers: { "Content-Type": "application/json"}, 
    load : function(result) { 
},