Get请求和Post请求的区别:
1、使用get请求时,参数在url中可见;而使用post不可见,自带加密
2、使用get发送请求的数据量比较小;使用post请求数据量比较大;
get请求的js代码:
function click() { var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); var username = document.getElementById("username").value; var
= document.getElementById("userpassword").value;userpassword
//添加参数,以求每次访问不同的url,以避免缓存问题
xmlHttp.open("get", "Server.aspx?username=" + encodeURIComponent(username) + "&
userpasswordxmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { document.getElementById("result").innerHTML = xmlHttp.responseText; } }=" + encodeURIComponent(age) + "&random=" + Math.random());
//发送请求,参数为null xmlHttp.send(null);}
post请求:
function click() { var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); var username = document.getElementById("txt_username").value; var
password
= document.getElementById("password").value;var data = "username=" + encodeURIComponent(username) + "&password
=" + encodeURIComponent(
password//不用担心缓存问题 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方法时,却需赋予其参数;
何时使用Get请求,何时使用Post请求
Get请求的目的是给予服务器一些参数,以便从服务器获取列表.例如:list.aspx?page=1,表示获取第一页的数据
Post请求的目的是向服务器发送一些参数,例如form中的内容.
Ajax请求的步骤:
1、创建一个XMLHttpRequest对象:
var request=new xmlHttpRequest();
2、设置请求参数:
request.open(‘get’,"请求的地址",true)
3、设置回调函数:
request.onreadstatechange=function(){
if(request.readystate==4&&request.status==200){
var str=request.responseText;
if(str=='1'){
$('id').innerHTML=""
}}
}