Ajax的面向对象的封装(ES5和ES6)ajax+php

我们来捋一下Ajax的概念,JS语言是单线程的语言、异步与同步。

JS是一门单线程的语言,所以JS语言写出来的程序也是单线程的程序。

学习ajax首先需要了解在编程中的异步与同步的概念。

异步和同步

  • 同步:程序发出请求需要等待当前请求执行结束才能进行下一步的操作。

  • 异步:程序发出请求不需要等待当前请求结束就能进行下一步的操作。

ajax的实现

我们要完成一个基本的ajax交互操作只需要四步即可。

  • 创建异步对象:

     let xhr = new XMLHttpRequest();

  • 指定请求的方式/端口/文件:

     xhr.open('get','./a.txt',true);

  • 发送请求:

      xhr.send();

  • 异步对象监听状态的变化(通过状态码):

       xhr.addEventListener('readystatechange',function(e){

                  if( xhr.readyState == 4 ){

                           console.log(xhr.responseText);

                  }

         } ,false);

0:请求为初始化

1:服务器连接已建立

2:请求已接收

3:请求处理中

4:请求已完成,且响应已就绪

这是最基本的实现,然后接下来进行对ajax的封装,使用es5和es6的两种方式进行面向对象的封装:

<script>
		let a = new ajax({
			url:"./../地址",// 必填
			method:"post",// 选填
			data:"数据"    // 这是 参数
			//相当于 对象参数的一样的参数
		}).then(function(data){
			// data就是后台响应回来的数据
			console.log(data)
		})
	</script>

es5的方式


function ajax(options){
	// 初始化数据
	this.url = options.url
	this.method = options.method || "get"
	this.data = options.data || {}

	// 创建xhr
	this.xhr = new XMLHttpRequest()

	if( this.method === "get" ){// get
		this.get()
	}else{// post
		this.post()
	}
}

// 构造函数原型上的属性和方法将来都可以被该构造函数下所创建的对象所共有
ajax.prototype.get = function(){
	// 对象的方法 this 指向了对象本身
	this.xhr.open("get",this.url+"?"+this.data,true)
	this.xhr.send()
}
ajax.prototype.post = function(){
	// 对象的方法 this 指向了对象本身
	this.xhr.open("post",this.url)
	this.xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
	this.xhr.send(this.data)
}
ajax.prototype.then = function(fn){
	this.xhr.onreadystatechange = function(){
		// this指向了事件的触发者, a.xhr
		if( this.readyState === 4 && this.status === 200 ){
			fn(this.responseText)
		}
	}
}


es6的方式:

class ajax{
	constructor(options){
		// 对象的解构赋值
		let{ method="get",url,data="" } = options

		// 创建xhr
		this.xhr = new XMLHttpRequest()

		// 判断
		if( method === "get" ){
			this.get(url,data)
		}else{
			this.post(url,data)
		}
	}
	// 在ES6的class类中的写法,原型上的方法是和构造器同级的
	get(url,data){
		this.xhr.open("get",url+"?"+data,true)
		this.xhr.send()
	}
	post(url,data){
		this.xhr.open("post",url,true)
		this.xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
		this.xhr.send(data)
	}
	then(fn){
		this.xhr.onreadystatechange = ()=>{
			if( this.xhr.readyState === 4 && this.xhr.status === 200 ){
				fn(this.xhr.responseText)
			}
		}
	}
}

感谢关注!

猜你喜欢

转载自blog.csdn.net/liliang250/article/details/109239333
今日推荐