前端向后端请求数据越来越频繁,ajax的使用显得尤为重要,一个好的ajax封装函数,对于数据请求会事半功倍
普通的ajax请求:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
console.log(xhr.responseText);
}
xhr.open("GET",url);
xhr.send();
以上就是ajax的get请求方式,就是简单的几句话,但是数据比较少。
优化一下:
function ajax(path,data = {},methon = 'get'){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
console.log(xhr.responseText);
}
var str = '';
for(var prop in data){
str += prop+"="+data[prop]+"&";
}
str.substr(0,str.length-1);
if(methon.toLowerCase() === 'get'){
xhr.open("get",path+"?"+str);
xhr.send();
}else{
xhr.open(methon,path)'
xhr.send(str);
}
}
ajax("http://www.xxxx.com",{username:123,password:456})
上面对应ajax做了简单的优化,下面的最终版。
最终版:
function ajax(options){
var {path,data = {},method = 'get',successFn,beforeFn = null} = options;
var xhr = new XMLHttpRequest();
var nowtime = new Date().getTime(),str = '';
for(var prop in data){
str+=prop +"=" + data[prop] + "&";
}
xhr.onreadystatechange = function() {
if(xhr.status == 200 && xhr.readyState == 4){
var datas = xhr.responseText;
try{
datas = JSON.parse(datas);
}catch(e){
}
successFn && successFn(datas);
}else{
beforeFn && beforeFn();
}
}
if(method.toLowerCase() === 'get'){
str = str + "nowtime="+nowtime;
xhr.open(method,`${path}?${str}`);
xhr.send();
}else{
xhr.open(method,path);
str = str.slice(0,-1);
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(str);
}
}
var options = {
path:"http://www.xxxx.com",
successFn:function(res){
console.log(res);
}
}
ajax(options);
最终版的ajax函数,可以应对更多的需求,变得更加灵活,还有就是利用promise对ajax进行封装。