ajax原生、jquery封装、promise封装

ajax已有原生和jQuery的写法,jQuery的写法已经相对很简单了。但是现在还需借助promise对ajax的封装来对aja有更深入的了解。

原生写法

// get
// 发送ajax的请求
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
	   if(xhr.readyState == 4){
	       if(xhr.status == 200){
	           doResponse(xhr);
	       }
	   }
}
xhr.open('GET',`01-reg-get.php?username=${username}`,true);
xhr.send(null);

// post
var xhr = new XMLHttpRequest();
// 状态监听
xhr.onreadystatechange = function(){
	    if(xhr.readyState == 4 && xhr.status == 200){
	        callback(xhr);
	    }
}
// 3设置请求的路径
xhr.open('POST','02-add-post.php');
// 3.5 设置请求头部
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// 4 发送post请求的参数
xhr.send('stuName=' + stuName + '&score=' + score);
 }

jQuery写法

$.ajax({
       url: "请求路径",
       type : "请求类型",
       datatype : 'jsonp', // 跨域解决
       data : { // 参数
           username : "cress",
           password : "123456"
       },
       success : function(res){ // 请求成功的返回
           console.log(res.data);
       },
       error : function(e){ // 请求失败的返回
           console.log(e);
       },
       complete : function(){ // 不管成功与否都会执行此函数
           console.log('complete');
           console.log(this);
       },
       context : $('div'), // 改变当前环境上下文 this
       timeout : 1000, // 请求的时长  在这段时间内  既没有成功也没有失败就会断开请求 但是complete还会执行
       async : true // 是否异步  一般为异步
});

promise封装
首先promise会返回两种状态,正好可以模拟ajax的两种返回状态。

function getJSON(type, url, data == null) {
	// 创建并返回promise
	return new Promise(function(resolve, reject) {
	
		// 创建ajax对象
		let xhr = new XMLHttpRequest();
		// 设置请求路径和请求参数
		xhr.open(type, url, true);
	
		// post 请求设置请求头
		if(type === "POST" || type === "post"){
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}
	
		// 事件监听
		xhr.onreadystatechange = function() {
			if (this.readyState !== 4) return;
	
			// 根据响应情况返回相应的promise状态
			if (this.status === 200) {
				resolve(this.response);
			} else {
				reject(new Error(this.statusText));
			}
	
		};
	
		// 设置错误监听函数
		xhr.onerror = function() {
			reject(new Error(this.statusText));
		};
	
		// 设置响应的数据类型
		xhr.responseType = "json";
	
		// 发送 http 请求
		xhr.send(data);
	});
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值