Ajax中Get請求與Post請求的區別css
寫在前面的話
咱們在使用Ajax時,當咱們向服務器發送數據時,咱們能夠採用Get方式請求服務器,也能夠使用Post方式請求服務器.那麼,咱們何時該採用Get方式,何時該採用Post方式呢?
Get請求和Post請求的區別
1.使用Get請求時,參數在URL中顯示,而使用Post方式,則不會顯示出來
2.使用Get請求發送數據量小,Post請求發送數據量大
例子
頁面的HTML代碼: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>app
區別:dom
Get請求:
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);
}post
Post請求:
function btn_post_click() {url
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)
{code
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"],可是此方法存在一個問題