1. Ajax
Concept
First of all, let's talk about what it is Ajax
. Its full name is async JavaScript and XML, which translates to "asynchronous JavaScript and XML". Many people mistakenly think that Ajax is a way to send requests or that Ajax and XMLHttpRequest are The same, in fact, this idea is wrong. Ajax is a technical term and a conceptual model. It is a tool for the client and the server to send messages and receive responses. It is a new method of using existing standards. One of its features is to achieve partial page refresh.
1.1 Synchronous and asynchronous
Ajax
It is a function of the default asynchronous execution mechanism. AJAX is divided into synchronous (async=false) and asynchronous (async=true)
1) Synchronous request
A synchronous request means that after the current request occurs, the browser cannot do anything or execute subsequent states until the request completes and returns data. That is to say, when the js code is loaded into the current Ajax, all the code in the page will be Stop loading, and the page will be in a state of suspended animation
Only when Ajax is executed can the state of suspended animation be lifted
2) Asynchronous request
By default, it is asynchronous, which means that when an asynchronous request occurs, the browser can do anything without affecting page loading and user operations
2. Ajax
Advantages
- Native js can be used
- Data can be updated without refreshing the page
- Can reduce the burden on the server and broadband
3. Ajax
How it works
Operating procedures
- An event occurs on the page (e.g. page load, button click...)
- js creates an XMLHttpRequest object
- The XMLHttpRequest object sends a request to the web server
- The server handles the request
- The server sends the response back to the web page
- js read response
- js to perform the correct action (such as page update)
4. Ajax
Use of
1) Send a request to the server
// 1. 创建 xmlHttpRequest 对象
let xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp = new XMLHttpRequest();
} else {
// IE6, IE5 浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2. 设置回调函数
xmlHttp.onreadystatechange = callback;
// 3. 使用 open 方法与服务器建立连接
xmlhttp.open(method, url, async);
/*
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
*/
// 添加请求头信息(可选)
xmlhttp.setRequestHeader(header, value);
// 4. 使用 send 方法发送请求
xmlhttp.send(string);
/*
string:仅用于 POST 请求,格式可以为 multipart/form-data,JSON,XML
*/
The above steps can only send the request to the server. If we want to respond to the client, there must be two prerequisites, namely:
- This http request is successful
- ajax request succeeded
can be judged by their respective status codes
2) Processing for different states
function callback() {
if (xmlHttp.readyState == 4) {
//判断交互是否成功
/*
readyState属性:表示请求/响应过程的当前阶段
0:未初始化。尚未调用 open()方法。
1:启动。已经调用 open()方法,但尚未调用 send()方法。
2:发送。已经调用 send()方法,但尚未接收到响应。
3:接收。已经接收到部分响应数据。
4:完成。已经接收到全部响应数据,而且已经可以在客户端使用了。
只有在XMLHttpRequest对象完成了以上5个步骤之后,才可以获取从服务器端返回的数据。
*/
if (xmlHttp.status == 200) {
/*
status属性:响应的 HTTP 状态码,常见的状态码如下
200:响应成功
301:永久重定向/永久转移
302:临时重定向/临时转移
304:本次获取内容是读取缓存中的数据
400:请求参数错误
401:无权限访问
404:访问的资源不存在
*/
//服务器的响应,可使用 XMLHttpRequest 对象的 responseText(获得字符串形式的响应数据) 或
// responseXML (获得 XML 形式的响应数据) 属性获得
let responseText = xmlHttp.responseText;
} else {
// 失败,根据响应码判断失败原因
}
}
}
3) API usage that responds to success and failure
//响应成功
xmlHttp.onload = function () {
};
//等效于
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
}
}
};
//响应失败
xmlHttp.onerror = function () {
};
//等效于
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status !== 200) {
}
}
};
5. Examples
// 将前端请求接口单独提取出来,方便复用和调整
//此接口可以改变
const BASE_URL="http://localhost:3000";
export default function Ajax({
// 请求参数配置
method="GET",
// 默认为'get'请求
url,
data={
},
}){
return new Promise ((resolve)=>{
// 通过Promise返回异步请求
// 创建一个ajax对象
const xhr=new XMLHttpRequest();
/**
* xhr对象中的open方法用来配置请求信息,建立对服务器的调用
* xhr.open('请求⽅式', '请求地址', 是否异步)
*/
xhr.open(method,BASE_URL+url);
// XMLHttpRequest提供的响应成功时api的使用
xhr.onload=function(){
resolve(JSON.parse(xhr.response));
};
// XMLHttpRequest提供的响应失败时api的使用
xhr.onerror=function(){
// 最后进行错误处理
if(xhr.status==0){
}
};
//发送请求
xhr.send(JSON.stringify(data));
});
}