使用jQuery的$.post方法可以以POST形式向服務器發起AJAX請求。$.post方法是jQuery的實用工具方法。
$.post方法語法
$.post(url,parameters,callback) |
|
參數 |
|
url |
(字符串)服務器端資源地址。 |
parameter |
(對象)需要傳遞到服務器端的參數。 參數形式為“鍵/值”。 |
callback |
(函數)在請求完成時被調用。該函數參數依次為響應體和狀態。 |
返回值 |
XHR實例 |
看個簡單的例子
客戶端代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<
head
>
<
title
></
title
>
<
script
src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></
script
>
<
script
type="text/javascript">
$().ready(function () {
$('#selectNum').change(function () {
var idValue = $(this).val();
//采用POST方式調用服務
$.post('Server.aspx', { id: idValue }, function (text, status) { alert(text); });
})
})
</
script
>
</
head
>
<
body
>
<
select
id="selectNum">
<
option
value="0">--Select--</
option
>
<
option
value="1">1</
option
>
<
option
value="2">2</
option
>
<
option
value="3">3</
option
>
</
select
>
</
body
>
</
html
>
|
服務端主要代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(!Page.IsPostBack)
{
if
(Request[
"id"
] !=
null
&& !
string
.IsNullOrEmpty(Request[
"id"
].ToString()))
{
Response.Write( GetData(Request[
"id"
].ToString()));
}
}
}
protected
string
GetData(
string
id)
{
string
str =
string
.Empty;
switch
(id)
{
case
"1"
:
str +=
"This is Number 1"
;
break
;
case
"2"
:
str +=
"This is Number 2"
;
break
;
case
"3"
:
str +=
"This is Number 3"
;
break
;
default
:
str +=
"Warning Other Number!"
;
break
;
}
return
str;
}
|
運行程序,結果如圖:
用httpwatcher攔截請求信息,當下拉框中選擇數字時,可以截取到如下請求信息。
使用$.post方法時的截圖:
通過上圖我們可以看到在POST Data里面有參數,說明這是一次POST請求。
在服務器端狀態有改變,或者是修改更新某些數據時多用POST請求。