天天看點

ajax post傳值,如何在$ ajax POST中傳遞參數?

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使用時觀察到的行為。