ajax的封装及优化

前端向后端请求数据越来越频繁,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进行封装。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值