我已按照此鏈接中所述的教程進行操作。在下面的代碼中,由于某種原因,數據不會作為參數附加到url上,但是如果我使用/?field1="hello"它直接將它們設置為url 則可以。$.ajax({ url: 'superman', type: 'POST', data: { field1: "hello", field2 : "hello2"} , contentType: 'application/json; charset=utf-8', success: function (response) { alert(response.status); }, error: function () { alert("error"); } });
3 回答

紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
Jquery.ajax不會像對GET數據那樣自動為您編碼POST數據。jQuery希望您的數據經過預格式化,以附加到請求正文中,以直接通過網絡發送。
一種解決方案是使用jQuery.param函數來構建查詢字符串,大多數處理POST請求的腳本都希望使用該字符串。
$.ajax({
url: 'superman',
type: 'POST',
data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
在這種情況下,該param方法會將數據格式化為:
field1=hello&field2=hello2
該Jquery.ajax文檔中說,有一個叫標志processData控制該編碼是否是自動還是沒有這樣做。該文檔說它默認為true,但這不是我在POST使用時觀察到的行為。
- 3 回答
- 0 關注
- 7336 瀏覽
添加回答
舉報
0/150
提交
取消