前端项目经常会用ajax,jQuery、fetch、axios等都对ajax进行了封装,很好用,不过有时候我们只想做个很简单的页面,只想用原生JavaScript写,不想引入任何框架,这个时候就需要直接用JavaScript的XMLHttpRequest对象直接发起网络请求了,其实很简单,不到50行代码吧,下面还是先上代码。
/**
* ajax请求
* by sdxjwkq01
*/
class ajax{
/**
* [get get请求]
* @param {[string]} url [地址]
* @param {[function]} callBack [回调函数]
* @return {[void]} [void]
*/
static get(url,callBack){
let xmlHttp=new XMLHttpRequest();
xmlHttp.open("GET",url,true);
xmlHttp.setRequestHeader("Content-Type","application/json");
xmlHttp.send();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
let returnData=null;
try{
returnData=JSON.parse(xmlHttp.responseText);
}catch(e){
returnData=xmlHttp.responseText;
}
callBack(returnData);
}
}
}
/**
* [post description]
* @param {[string]} url [地址]
* @param {[JSON]} data [发送数据]
* @param {[function]} callBack [description]
* @return {[void]} [void]
*/
static post(url,data,callBack){
let xmlHttp=new XMLHttpRequest();
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-Type","application/json");
xmlHttp.send(JSON.stringify(data));
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
let returnData=null;
try{
returnData=JSON.parse(xmlHttp.responseText);
}catch(e){
returnData=xmlHttp.responseText;
}
callBack(returnData);
}
}
}
}
具体用法也很简单,比如get请求
ajax.get("http://xxx.com?q=xx",function(data){
console.log(data);
})
post请求
ajax.post("https://xxx.com",{
a:"xxx",
b:1
},function(data){
console.log(data);
})