ajax请求细分的话可以分为5个步骤:
-
获取XMLHttpRequest对象
let xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else{ xhr = new ActiveXObject("Mricosoft.XMLHTTP"); }
- 创建一个请求
xhr.open(type,url,async)
-
发送状态
xhr.send(null) get xhr.send(params) post
-
捕获请求状态
xhr.onreadystatechange = function (){ }
-
接受返回值
if(xhr.readyState == 4 && xhr.status == 200){ options.success(xhr.responseText); }
ajax完整的封装:
let baseURL = 'http://localhost:3000/';
function ajax(options){
let xhr = null;
let params = paramsHandle(options.data);
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if(options.type == "GET"){
xhr.open(options.type,baseURL+options.url + "?"+ params,options.async);
xhr.send(null)
} else if(options.type == "POST"){
xhr.open(options.type,baseURL+options.url,options.async);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(params);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
options.success(xhr.response);
}
}
}
function paramsHandle(data){
let arr = [];
for(let key in data){
arr.push(key + "=" + data[key]);
}
return arr.join("&");
}
ajax的使用:
ajax({
url : "login",
type : "POST",
async : true,
data : {
name : "zhangsan",
password : "123456"
},
success : function(res){
console.log(res);
}
})