用jQuery發送JSON數據為什么下面的代碼發送數據為City=Moscow&Age=25而不是JSON格式?var arr = {City:'Moscow', Age:25};$.ajax(
{
url: "Ajax.ashx",
type: "POST",
data: arr,
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
3 回答

四季花海
TA貢獻1811條經驗 獲得超5個贊
var arr = { City: 'Moscow', Age: 25 };$.ajax({ url: 'Ajax.ashx', type: 'POST', data: JSON.stringify(arr), contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, success: function(msg) { alert(msg); }});
使用 JSON.stringify
方法將javascript對象轉換為JSON字符串,JSON字符串是本機并內置到現代瀏覽器中的。如果您想支持舊的瀏覽器,您可能需要包括 控件指定請求內容類型。 contentType
屬性,以便向服務器指示發送JSON請求的意圖。 這個 dataType: 'json'
屬性用于您希望從服務器獲得的響應類型。jQuery足夠聰明 猜
它來自服務器 Content-Type
響應頭。因此,如果您有一個Web服務器,它或多或少地尊重HTTP協議,并使用 Content-Type: application/json
對于您的請求,jQuery將自動將響應解析為javascript對象到 success
回調,這樣您就不需要指定 dataType
財產。
你所說的 arr
是 不是數組
..它是一個具有屬性的javascript對象( City
和 Age
)。數組用 []
在javascript里。例如 [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]
是一個由兩個對象組成的數組。

幕布斯7119047
TA貢獻1794條經驗 獲得超8個贊
$.postJSON = function(url, data, success, args) { args = $.extend({ url: url, type: 'POST', data: JSON.stringify(data), contentType: 'application/json; charset=utf-8', dataType: 'json', async: true, success: success }, args); return $.ajax(args);};$.postJSON('test/url', data, function(result) { console.log('result', result);});
- 3 回答
- 0 關注
- 326 瀏覽
添加回答
舉報
0/150
提交
取消