AJAX

Ajax(Asynchronous Javascript And XML)即异步的 JavaScript 和 XML,是浏览器与服务器之间的一种异步通信方式。它可以在不重新加载整个网页的情况下,对页面的某部分进行局部更新。

核心在于:**Ajax 通过 XMLHttpRequest 对象实现异步通信,让浏览器在等待服务器响应的同时不阻塞当前页面**,从而显著提升交互体验。

传统方式每次获取数据都需要整页刷新、等待期间页面无法操作;Ajax 解决了这一痛点,实现了无刷新更新页面。
前端技术 · AJAX / XHR / Axios 实战笔记

1. 概述

1.1 什么是 AJAX

在 JS 中有内置的构造函数来创建 ajax 对象。创建 ajax 对象以后,我们就使用 ajax 对象的方法去发送请求和接受响应。

Ajax 的一个最大特点是无需刷新页面便可向服务器传输或读写数据(又称无刷新更新页面),这一特点主要得益于 XMLHTTP 组件。

异步的 JavaScript,它可以异步地向服务器发送请求,在等待响应的过程中,不会阻塞当前页面,在这种情况下,浏览器可以做自己的事情。直到成功获取响应后,浏览器才开始处理响应数据。

所以简单来说,Ajax 就是在浏览器不重新加载网页的情况下,对页面的某部分进行更新。

1.2 XMLHttpRequest 对象

原生 AJAX 的核心是 XMLHttpRequest(简称 XHR)对象,它是浏览器提供的用于与服务器进行异步通信的内置构造函数。

**核心概念** XMLHTTPRequest 是 Ajax 实现异步、无刷新通信的基础组件。

2. 基于原生 XHR 的请求

2.1 搭建 Express 服务

在学习 Ajax 中我们用到 express 框架,我们先引入 express:

npm init --yes
npm -i express

设置完成后我们引入 express,并且创建 express 对象:

/* 引入express */
const express = require('express');
/* 创建对象 */
const app = express();

/* 创建路由规则 */
/* 对请求报文的封装
对响应报文的封装 */
app.get("/serve",(request,response)=>{
    /* 设置响应头 设置允许跨域访问 */
    response.setHeader('Access-Control-Allow-Origin','*');
    /* 设置响应体 */
    response.send("Hello");
})

/* 监听端口启动服务 */
app.listen(8030,()=>{
    console.log("服务启动");
})

2.2 发送 GET 请求

const btn = document.querySelector("button");
const result = document.querySelector(".box");
btn.addEventListener("click",function(){
    /* 创建对象 */
    const xhr = new XMLHttpRequest()
    /* 初始化 设置请求方法和url */
    xhr.open('GET',"http://localhost:8030/serve");
    /* 发送  */
    xhr.send();
    /* 事件绑定 */
    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState === 4)
        {
            if (xhr.status >= 200 && xhr.status < 300){
                /*                     console.log(xhr.status);
                    console.log(xhr.statusText); */
                result.innerHTML=xhr.response;
            }else {

            }
        }
    })

2.3 xhr.readyState 状态码

ajax 状态码用于标识请求/响应过程中的不同阶段:

状态码 说明
readyState === 0 未初始化完成,也就是 open 方法还没有执行
readyState === 1 配置信息已经完成,也就是执行完 open 之后
readyState === 2 send 方法已经执行完成
readyState === 3 正在解析响应内容
readyState === 4 响应内容已经解析完毕,可以在客户端使用

在当 === 4 时我们使用服务端给我们的数据。

2.4 readystatechange 事件

这个事件是专门用来监听 ajax 对象的 readyState 值改变的行为。也就是说只要 readyState 的值发生变化了,就会触发该事件。所以我们就在这个事件中来监听 ajax 的 readyState 是不是 4。

2.5 GET 请求设置参数

xhr.open('GET',"http://localhost:8030/serve?a=100&b=200");

2.6 POST 请求

const div =document.querySelector("div");

div.addEventListener("mousemove",function(){
    const xhr = new XMLHttpRequest();
    xhr.open('POST',"http://localhost:8030/serve");
    xhr.send();

    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState === 4){
            if (xhr.status >= 200 && xhr.status <300){
                div.innerHTML=xhr.responseText;
            }else{

            }
        }
    })
})

对应在服务端为 POST 添加路由:

app.post("/serve",(request,response)=>{
    /* 设置响应头 设置允许跨域访问 */
    response.setHeader('Access-Control-Allow-Origin','*');
    /* 设置响应体 */
    response.send("Hello AJAX POST");
})

2.7 POST 设置请求参数

xhr.send("a=100&b=200&c=300");

xhr.send('a:100&b:200&c:300');

2.8 设置请求头信息

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
response.setHeader('Access-Control-Allow-Headers','*')

2.9 接收与解析 JSON

<div class="box"></div>
<script>
    const div = document.querySelector(".box");
window.addEventListener("keydown",function(){
    const xhr = new XMLHttpRequest();

    xhr.open("POST","http://localhost:8030/serve");
    xhr.send();
    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState===4){
            if (xhr.status >=200 && xhr.status <300){
                /* 手动转换 */
                const data = JSON.parse(xhr.responseText);
                div.innerHTML=data.name;
                /* 自动转换 */
                console.log(xhr.response);
                div.innerHTML=xhr.response
            }else{

            }
        }
    })
})
app.all("/serve",(request,response)=>{
    /* 设置响应头 设置允许跨域访问 */
    response.setHeader('Access-Control-Allow-Origin','*');
    //响应头
    response.setHeader('Access-Control-Allow-Headers','*')
    /* 设置响应体 */
    const data = {
        name:"ikun"
    }
    let str = JSON.stringify(data);
    response.send(str);
})
**JSON 转换** 既可以用 `JSON.parse(xhr.responseText)` 手动转换,也可以依赖响应自动转换后直接读取 `xhr.response`。

2.10 使用 nodemon 自动重启

由于之前每次修改 serve.js 都要重新启动,所以我们使用 nodemon:

npm install -g nodemon
nodemon serve.js
//如果报错
npx nodemon serve.js

2.11 解决 IE 缓存问题

xhr.open("POST","http://localhost:8030/serve?t="+Date.now());

3. 请求超时、取消与防重复

3.1 请求超时与网络异常处理

const div = document.querySelector(".box");
window.addEventListener("keydown",function(){
    const xhr = new XMLHttpRequest();

    xhr.open("POST","http://localhost:8030/delay");
    xhr.send();

    xhr.timeout=2000;

    xhr.addEventListener("timeout",function(){
        alert("网络异常");
    })
    xhr.addEventListener("error",function(){
        alert("网络断开连接");
    })

    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState===4){
            if (xhr.status >=200 && xhr.status <300){
                div.innerHTML=xhr.response;
            }else{

            }
        }
    })
})

3.2 取消请求

xhr.abort();

3.3 解决重复请求

const btn1 = document.querySelector(".send");
const btn2 = document.querySelector(".done");
let x=null;
let isSending=false;
btn1.addEventListener("click",function(){
    if (isSending) x.abort();
    x= new XMLHttpRequest();    
    x.open("GET","http://177.0.0.1:8000/delay");
    x.send();
    isSending=true;
    x.addEventListener("readystatechange",function(){
        if (x.readyState==4){
            isSending=4;
        }
    })
})
btn2.addEventListener('click',function(){
    x.abort();
})
**重复请求** 通过 `isSending` 标记与 `x.abort()` 配合,可在发起新请求前取消仍在进行的旧请求,避免重复响应覆盖。

4. Axios 的使用

4.1 使用 json-server 搭建测试接口

npm i -g json-serve

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .btns .btn1{
            height: 20px;
            line-height: 20px;
            background-color: red;
            width: 150px;
            text-align: center;
        }
        .btns .btn2{
            height: 20px;
            line-height: 20px;
            background-color: blue;
            width: 150px;
            text-align: center;
        }
        .btns .btn3{
            height: 20px;
            line-height: 20px;
            background-color: green;
            width: 150px;
            text-align: center;
        }

        .btns .btn4{
            height: 20px;
            line-height: 20px;
            background-color: yellow;
            width: 150px;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>axios的基本使用</h1>
    <div class="btns">
        <button class="btn btn1">Get</button>
        <button class="btn btn2">Post</button>
        <button class="btn btn3">Put</button>
        <button class="btn btn4">Delete</button>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        //console.log(axios);
        const btns = document.querySelectorAll(".btn");

        btns[0].addEventListener('click',function(){
            axios({
                method: 'GET',
                url:"http://localhost:3000/posts/2"
            }).then(response=>{
                console.log(response);
            })
        })

        btns[1].addEventListener('click',function(){
            axios({
                method: 'POST',
                url:"http://localhost:3000/posts",
                data:{
                    id:'3',
                    title:"The weather is so nice",
                    author:'rc'
                }
            }).then(response=>{
                console.log(response);
            })
        })

        btns[2].addEventListener('click',function(){
            axios({
                method: 'PUT',
                url:"http://localhost:3000/posts/3",
                data:{
                    title:"The weather is so nice",
                    author:'richu'
                }
            }).then(response=>{
                console.log(response);
            })
        })

        btns[3].addEventListener('click',function(){
            axios({
                method: 'DELETE',
                url:"http://localhost:3000/posts/3",
            }).then(response=>{
                console.log(response);
            })
        })
    </script>
</body>
</html>

4.2 axios.post 等快捷方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .btns .btn1{
            height: 20px;
            line-height: 20px;
            background-color: red;
            width: 150px;
            text-align: center;
        }
        .btns .btn2{
            height: 20px;
            line-height: 20px;
            background-color: blue;
            width: 150px;
            text-align: center;
        }
        .btns .btn3{
            height: 20px;
            line-height: 20px;
            background-color: green;
            width: 150px;
            text-align: center;
        }

        .btns .btn4{
            height: 20px;
            line-height: 20px;
            background-color: yellow;
            width: 150px;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>axios的基本使用</h1>
    <div class="btns">
        <button class="btn btn1">Get</button>
        <button class="btn btn2">Post</button>
        <button class="btn btn3">Put</button>
        <button class="btn btn4">Delete</button>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        const btns = document.querySelectorAll(".btn");

        btns[0].addEventListener('click',function(){
            axios.request({
                method:'GET',
                url:"http://localhost:3000/posts/2"
            }).then((resonse)=>{
                console.log(resonse);
            })
        })

        btns[1].addEventListener('click',function(){
            axios.post(
                'http://localhost:3000/posts',
                {
                    id:'3',
                    title:"The weather is so nice",
                    author:'rc'
                }
            ).then(response=>{
                console.log(response);
            })
        })
    </script>
</body>
</html>

4.3 默认配置

/* 做默认配置 */
axios.defaults.method = 'GET';
axios.defaults.baseURL = 'http://localhost:3000/posts';

4.4 创建实例对象发送请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="btns">
        <button class="btn btn1">Get</button>
        <button class="btn btn2">Post</button>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        const btns = document.querySelector(".btn");

        const ax = axios.create({
            baseURL:'http://localhost:3000/posts',
            timeout:2000
        });
            
        ax({
            url:'/1'
        }).then((resonse)=>{
            console.log(resonse);
        })
    </script>
</body>
</html>

4.5 拦截器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        axios.interceptors.request.use(config => {
            console.log("成功");
            //return Promise.resolve(config);
            return config;
        },error => {
            console.log(error);
            return Promise.reject(error);
        });

        axios.interceptors.response.use(response => {
            console.log("成功");
            return response;
        },error => {
            console.log(error);
            return Promise.reject(error);
        });

        axios({
            method:'GET',
            url:'http://localhost:3000/posts'
        }).then(response=>{
            console.log(response);
        }).catch(reason=>{
            console.log(reason);
        })
    </script>
</body>
</html>
**Axios 速查** Axios 在原生 XHR 之上做了封装:支持 Promise 风格调用、默认配置、实例对象与请求/响应拦截器,更贴近现代前端开发习惯。

一句话总结:AJAX 通过 XMLHttpRequest(及封装库 Axios)实现浏览器与服务器的异步、无刷新通信,并借助状态码、超时、取消与拦截器等机制保证请求可控。