13、前端知识点--ajax原理以及实现过程

一、简略版的

Ajax简介

Ajax(Asyncchronous JavaScript and Xml),翻译过来就是说:异步的javaScript和xml, Ajax不是新的编程语言,而是一种使用现有标准的新方法。

Ajax的优点:在不重新加载整个页面的情况下,可以与服务器交换数据,并更新部分网页的艺术。

1. Ajax的工作原理

Ajax的工作原理相当于在用户和服务器之间加了一个中间层(Ajax引擎),使用户操作与服务器响应异步化。并不是所有用户请求都提交服务器。像一些数据验证和数据处理等都交给Ajax引擎自己来做,只有确定需要从服务器读取新数据时再由Ajax引擎代为向服务器提交请求。
来看看和传统方式的区别:
  

Ajax与服务器通信有一个核心的对象XMLHttpRequest,在IE低版本浏览器是使用ActiveXObject来实现 。

XMLHttpRequest对象的几个常用的属性

1. readyState属性

readyState属性存在有服务器响应的状态信息。每当readyState改变时,onreadystatechange函数就会被执行。readyState属性的值有:

 

2. onreadystatechange 属性

onreadystatechange属性存在有处理服务器响应的函数。下面的代码定义一个空的函数,可同时对onreadystatechange属性进行设置:

xhr.onreadystatechange = function() {

}

3. status 属性

status是服务器状态码(如:404: 文件未找到, 200: 成功等)

4. statusText 属性

服务器返回状态文件信息, HTTP状态码的相应文本(OK或Not Found)

5. responseText 属性

可以通过responseText属性来取回由服务器返回的数据。

xhr.onreadystatechange = function() {
	if (xhr.readyState === 4 && xhr.status === 200) {
		console.log(xhr.responseText)
	}
}

XMLHttpRequest对象上的属性总览:

XMLHttpRequest对象上的方法

1. open()方法

open()有三个参数,第一个参数定义发送请求所使用的方法,第二个参数规定服务器端脚本的URL,第三个参数规定应当对请求进行异步地处理。

xhr.open('GET', 'test.php', true)

2. send()方法

xhr.send(null)

如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据。
xhr.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded;charset=UTF-8”);

3. 其他方法

2. Ajax实现步骤

要实现Ajax,大体上有四个步骤:

创建XMLHttpRequest
设置请求方式
调用回调函数
发送请求
function ajax(url, data, method='POST', async=true) {
	return new Promise((resolve, reject) {
		// 第一步,创建xmlHttpRequest
		let xhr = null
		if (window.XMLHttpRequest) {
			// 支持XMLHttpRequest
			xhr = new XMLHttpRequest()
		} else {
			// IE5或者IE6
			xhr = new ActiveXObject('Microsoft.XMLHTTP')
		}

		// 第二步,设置请求方式
		xhr.open(method, url, async)

		// 第三步, 调用回调函数
		xhr.onreadyStateChange = function() {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					resolve(xhr.responseText)
				} else {
					reject(xhr.statusText)
				}
			} else {
				reject(xhr.statusText)
			}
		}

		// 第四步, 发送请求
		xhr.send(data)
	})
}

详细版一:https://blog.csdn.net/weixin_37580235/article/details/81459282

AJAX的实现步骤(完整过程):https://blog.csdn.net/qq_29569183/article/details/79259889

猜你喜欢

转载自www.cnblogs.com/jianguo221/p/11780667.html