Ajax中Get請求與Post請求的區別

來源:互聯網
上載者:User
寫在前面的話

我們在使用Ajax時,當我們向伺服器發送資料時,我們可以採用Get方式請求伺服器,也可以使用Post方式請求伺服器.那麼,我們什麼時候該採用Get方式,什麼時候該採用Post方式呢?

Get請求和Post請求的區別

1.使用Get請求時,參數在URL中顯示,而使用Post方式,則不會顯示出來

2.使用Get請求發送資料量小,Post請求發送資料量大

例子

頁面的HTML代碼:

<html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title>    <style type="text/css">        *        {            margin:8px;        }    </style></head><body>    <label for="txt_username">        姓名:</label>    <input type="text" id="txt_username" />    <br />    <label for="txt_age">        年齡:</label>    <input type="text" id="txt_age" />    <br />    <input type="button" value="GET" id="btn_get" onclick="btn_get_click();" />    <input type="button" value="POST" id="btn_post" onclick="btn_post_click();" />    <div id="result">    </div></body></html>

區別:

  Get請求 Post請求
用戶端腳


function btn_get_click() {var xmlHttp = window.XMLHttpRequest ?         new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");var username = document.getElementById("txt_username").value;    var age = document.getElementById("txt_age").value;    //添加參數,以求每次訪問不同的url,以避免緩衝問題    xmlHttp.open("get", "Server.aspx?username=" + encodeURIComponent(username)        + "&age=" + encodeURIComponent(age) + "&random=" + Math.random());xmlHttp.onreadystatechange = function () {        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {            document.getElementById("result").innerHTML = xmlHttp.responseText;        }    }    //發送請求,參數為null    xmlHttp.send(null);}
function btn_post_click() {var xmlHttp = window.XMLHttpRequest ?        new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");var username = document.getElementById("txt_username").value;    var age = document.getElementById("txt_age").value;                var data = "username=" + encodeURIComponent(username)        + "&age=" + encodeURIComponent(age);    //不用擔心緩衝問題    xmlHttp.open("post", "Server.aspx", true);    //必須設定,否則伺服器端收不到參數    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");xmlHttp.onreadystatechange = function () {        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {            document.getElementById("result").innerHTML = xmlHttp.responseText;        }    }    //發送請求,要data資料    xmlHttp.send(data);}

區別:

1.get請求需注意緩衝問題,post請求不需擔心這個問題

2.post請求必須設定Content-Type值為application/x-form-www-urlencoded

3.發送請求時,因為get請求的參數都在url裡,所以send函數發送的參數為null,而post請求在使用send方法時,卻需賦予其參數

對於用戶端代碼中都請求的server.aspx,我們來看server.aspx.cs中的代碼:

protected void Page_Load(object sender, EventArgs e){    string username = string.Empty;    int age = 0;    if (Request.HttpMethod.ToUpper().Equals("GET"))    {        username = Request.QueryString["username"];        age = int.Parse(Request.QueryString["age"]);    }    else    {        username = Request.Form["username"];        age = int.Parse(Request.Form["age"]);    }    Response.Clear();    Response.Write("姓名:'" + username + "'<br/>年齡:" + age + "<br/>時間:'" + DateTime.Now.ToString() + "'");    Response.End();}

此處,我們發現了get請求和post請求在伺服器端的區別:

在用戶端使用get請求時,伺服器端使用Request.QueryString來擷取參數,而用戶端使用post請求時,伺服器端使用Request.Form來擷取參數.

關於伺服器端擷取資料,我們還可以使用一個通用的擷取參數的方式即Request["username"],但是此方法存在一個問題,我們隨後來講.

下面,我們使用HttpWatch來看下,當使用get和post方式發送請求時,用戶端究竟發送了什麼,收到了什麼.

對於get請求和post請求中的時間差,請不要在意,因為是在不同時間按下的get按鈕和post按鈕.

  OverView
Get請求
Post請求

從請求的url可以看出,get請求是帶著參數的,post請求的url則不帶.

  Header
Get請求
Post請求

因為訪問的是同一個伺服器,所以從伺服器擷取的資訊都是一致的.但是用戶端發送的卻不一樣了.

  Header
Get請求
Post請求

從cache可以看出,get請求在發送後,即被緩衝,而post請求時 never cached.

  Query String
Get請求
Post請求

因為get請求的參數是在url中的,所以Query String中是有值的.而post請求則沒有.

  POST Data
Get請求
Post請求

在Post Data裡,因為get請求的字串是在url中附帶的,所以Post Data中無資料.

  Content(從伺服器擷取的資料)
Get請求
Post請求

從伺服器擷取的內容都是一致的.

    Stream
Get請求 發送給伺服器的

GET /AjaxWeb/Article7/Server.aspx?username=%E5%BC%A0%E4%B8%89&age=33&random=0.34838340505348675 HTTP/1.1
Accept: */*
Accept-Language: zh-cn
Referer: http://localhost/AjaxWeb/Article7/Ajax.htm
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET4.0C; .NET4.0E)
Host: localhost
Connection: Keep-Alive

從伺服器擷取的

HTTP/1.1 200 OK
Date: Sun, 05 Jun 2011 15:36:27 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 60

濮撳悕:'寮犱笁'<br/>騫撮緞:33<br/>鏃墮棿:'2011-6-5 23:36:27'

Post請求 發送給伺服器的

POST /AjaxWeb/Article7/Server.aspx HTTP/1.1
Accept: */*
Accept-Language: zh-cn
Referer: http://localhost/AjaxWeb/Article7/Ajax.htm
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET4.0C; .NET4.0E)
Host: localhost
Content-Length: 34
Connection: Keep-Alive
Cache-Control: no-cache

username=%E5%BC%A0%E4%B8%89&age=33

從伺服器擷取的

HTTP/1.1 200 OK
Date: Sun, 05 Jun 2011 15:47:39 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 60

濮撳悕:'寮犱笁'<br/>騫撮緞:33<br/>鏃墮棿:'2011-6-5 23:47:39'

比較一下,get請求的url帶參數,post請求的url不帶參數.post請求是不會被緩衝的.

現在,我們來思考另一個問題:

剛才我們說過,伺服器在接受參數時,可以採用一個通用的方法,即:Request["username"]來接受參數此方式可以接受get和post請求發送的參數,那麼,我們做個測試,在get請求中設定Content-Type,並且send方法中也發送了username=zhangsan,我們看看伺服器究竟是返回什麼值呢?修改伺服器代碼如下:

protected void Page_Load(object sender, EventArgs e){    string username = string.Empty;    int age = 0;    username = Request["username"];    age = int.Parse(Request["age"]);    Response.Clear();    Response.Write("姓名:'" + username + "'<br/>年齡:" + age + "<br/>時間:'" + DateTime.Now.ToString() + "'");    Response.End();}

用戶端中,修改btn_get_click()方法如下:

//直接輸入張三作為username參數的值xmlHttp.open("get", "Server.aspx?username=" + encodeURIComponent("張三")    + "&age=" + encodeURIComponent(age) + "&random=" + Math.random());//在get請求中添加Content-Type資訊xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");...//發送請求,並附帶username=zhangsanxmlHttp.send(username = "zhangsan");

測試代碼,結果輸出的是"張三".

同樣,緊接上面的代碼,我們再來做另一個測試,修改post請求,給open方法的url加一個username參數,值為zhangsan.

xmlHttp.open("post", "Server.aspx?username=zhangsan", true);

此時,我們再來運行項目,伺服器返回的結果是什麼呢?此時我們發現出現的結果是zhangsan.

當我們在get和post請求時,同時在url中、send方法的data中都放置了參數,為什麼擷取的總是url中的參數值呢?

答:在使用Request時,其會從QueryString,Form,ServerVariable中遍曆一番,如果發現符合要求的資料,那麼就會停止向後搜尋.所以,我們上例中擷取的username實際上都是url中的username值.

何時使用Get請求,何時使用Post請求

Get請求的目的是給予伺服器一些參數,以便從伺服器擷取列表.例如:list.aspx?page=1,表示擷取第一頁的資料

Post請求的目的是向伺服器發送一些參數,例如form中的內容.

下面使用執行個體來表示Get請求和Post請求在發送同一段資料時的區別.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.