Ajax请求原理解析
1:创建XMLHttpRequest对象
var xhr;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
2:准备请求
xhr.open(method,url,async);
method:get post
url:请求地址
async:true异步 false同步
3:发送请求
xhr.send();
get :xhr.open("GET",url,true);
xhr.send(null);
post:
xhr.open("POST",url,true);
xhr.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); //规定表头
xhr.send("name="+userName+"&age="+userAge);//参数
4:处理响应
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(“响应成功成功”,xhr.responseText);
}
} |
|