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"],可是此方法存在一个问题