Resumo dos formatos comumente usados de AJAX a AXIOS

protocolo HTTP

  • O protocolo detalha as regras pelas quais navegadores e servidores web se comunicam entre si
  • O navegador envia para o servidor, que se torna uma solicitação , e o conteúdo enviado se torna uma mensagem de solicitação
    • formato de pedido
行 : 包含:请求类型(GET、POST等)、url路径、HTTP版本
头	: 包含很多内容,固定格式是:[名字][英文冒号][空格][体]
空行
请求体:如果是GET请求,此处为空; 如果是POST请求,此处可以不为空

  • O servidor fornece ao navegador um resultado, que se torna uma resposta , e o conteúdo do resultado se torna uma mensagem de resposta
    • O formato da mensagem de resposta
行:包含:HTTP协议版本、响应状态码(200表示成功,404表示找不到网页)、响应状态字符串
头:格式跟请求头一样
空行
体:主要的返回内容,可以是html格式的

O uso geral e a demonstração do ajax requerem o download do node.js e o uso da estrutura expressa (como nosso front-end)

link para download do node.js: Node.js

site expresso: Express - Estrutura de desenvolvimento de aplicativos da Web baseada em Node.js - Documentação em chinês expresso | Rede em chinês expresso

Formato básico para enviar uma solicitação GET

    <script>
        // 获取button元素
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');
        // 绑定点击事件
        btn.onclick = function(){
            // 创建对象
            const xhr = new XMLHttpRequest();
            // 初始化 设置请求方法和 url
            xhr.open('GET','http://127.0.0.1:8000');
            // 发送
            xhr.send();
            // 时间绑定 处理服务器端返回的结果
            // 在onreadystatechange中
                // on 表示在什么的时候
                // readystate 是 xhr 对象中的属性,表示此时的状态,值有5个:0,1,2,3,4
            xhr.onreadystatechange = function(){
                // 判断是否返回了全部的结果
                if(xhr.readyState === 4){
                    // 判断响应状态码,200、404、403、401、500等
                    // 响应状态码在200~300之间的都表示成功
                    if(xhr.status >= 200 && xhr.status < 300){
                        // 处理结果 四部分(行、头、空行、体)
                        // console.log(xhr.status);// 状态码
                        // console.log(xhr.statusText);// 状态字符串
                        // console.log(xhr.getAllResponseHeaders);// 所有的响应头
                        // console.log(xhr.response);// 响应体
                        result.innerHTML = xhr.response;
                    }
                }
            }

        } 
    </script>

Definir parâmetros no URL

  • Use ? para conectar o endereço e a lista de parâmetros
  • Vários parâmetros com lista de parâmetros de concatenação
  • Por exemplo, preciso passar os três parâmetros a=100;b=200;c=300, a url escrevendo:
  • https://www.baidu.com?a=100&b=200&c=300

O formato básico de referência de quadro expresso em ajax

// 引入express
const express = require('express');
// 创建应用对象
const app = express();
// 创建路由规则
// requese是对请求报文的封装,response是对响应报文的封装
app.get('/',(request,response)=>{
    // 设置响应
    response.send("hello, express");
});
// 监听端口启动服务
app.listen(8000,()=>{
    console.log("服务已经启动,8000端口监听中...");
})

Em geral, você também precisa definir cross-domain

Formato básico para enviar uma solicitação POST

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POST 请求</title>
    <style>
        #result{
            width: 200px;
            height: 200px;
            border: 1px solid #903;
        }
    </style>
</head>
<body>
    <div id="result">
        <!--当把鼠标放在这个div上时,发送POST请求,将返回结果在div里面展示-->
    </div>

    <script>
        // 获取元素
        const result = document.getElementById('result');
        // 绑定事件
        result.addEventListener('mouseover',function(){
            // 创建对象
            const xhr = new XMLHttpRequest();
            // 初始化 设置请求类型和url】
            xhr.open('POST','http://127.0.0.1:8000');
            // 发送
            xhr.send('a=100&b=200&c=300');
            // 事件绑定
            xhr.onreadystatechange = function(){
                // 判断状态
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status < 300){
                        // 处理返回结果
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>
</html>

O formato dos parâmetros de configuração do POST é mais flexível, mas deve ser processado da maneira correspondente no lado do servidor

Precisa ser escrito entre colchetes de send

Todos os três acima

Processamento responsivo de dados json

No desenvolvimento, frequentemente encontramos coisas como

{'nome':'ayguigfu'};

Tais dados, é um objeto! Mas é muito inconveniente de lidar.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3-json</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid #903;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        const result = document.getElementById('result');
        window.onkeydown = function(){
            // 创建对象
            const xhr = new XMLHttpRequest();
            // 自动转换数据需要的设置响应数据的类型
            xhr.responseType = 'json';
            // 初始化
            xhr.open('GET','http://127.0.0.1:8000/json-server');
            // 发送
            xhr.send();
            // 事件绑定
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status < 300){
                       // 手动对数据做一个转换
                    //    let data = JSON.parse(xhr.response);
                    //    console.log(data);
                    //    result.innerHTML = data.name;
                    // console.log(xhr.response);
                    result.innerHTML = xhr.response.name;
                    }
                }
            }

        }
    </script>
</body>
</html>

No arquivo server.js, definimos um caminho especial e dados de resposta

app.get('/json-server',(request,response)=>{
  // 设置允许跨域
  response.setHeader('Access-Control-Allow-Origin', '*');
  // 响应一个数据
  const data = {
    name : 'atguigu'
  }
  // send 里面只能结束字符穿类型的,因此对data对象进行转换
  let str = JSON.stringify(data);
  // 设置响应体
  response.send(str);
});

Manipulação de tempo limite de rede e exceção de rede

Por vários motivos, nossas solicitações sempre encontrarão problemas. Pela experiência do usuário, não podemos ignorar

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络超时和异常</title>
    <style>
        #result{
            width: 200px;
            height: 200px;
            border: 1px solid #394;
        }
    </style>
</head>
<body>
    <button>点我发送请求</button>
    <div id="result"></div>
    <script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');

        btn.addEventListener('click',function(){
            const xhr = new XMLHttpRequest();
            // 请求超时设置 2s
            xhr.timeout = 2000;
            // 超时回调
            xhr.ontimeout = function(){
                alert('网络异常,请稍后重试');
            }
            // 网络异常回调
            xhr.onerror = function(){
                alert('您的网络似乎出了一点问题');
            }
            xhr.open('GET','http://127.0.0.1:8000/e');
            xhr.send();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status < 300){
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>
</html>

Em server.js, escrevemos uma regra separada

// 针对超时和网络异常
app.get('/e',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin', '*');
    // 设置响应体(3s之后再响应)
    setTimeout(()=>{
        response.send("延时响应");
    },3000);
});

Cancelar manualmente uma solicitação

Pergunta de solicitação duplicada

Antes do mesmo usuário e de usuários diferentes, a mesma solicitação pode ser enviada repetidamente, o que é muito hostil para o nosso servidor

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>重复请求问题</title>
    <style>
    </style>
</head>
<body>
    <button>点我发送请求</button>
    <script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');
        let isSending = false; // 标识是否正在发送请求
        let xhr = null;

        btn.addEventListener('click',function(){
            if(isSending == true) xhr.abort();
            xhr = new XMLHttpRequest();
            isSending = true;
            xhr.open('GET','http://127.0.0.1:8000/e');
            xhr.send();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    isSending = false;
                    if(xhr.status >= 200 && xhr.status < 300){
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>
</html>

solicitação de envio jQuery

Comparado com solicitações ajax nativas, o método encapsulado por JQuery será mais conveniente

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>重复请求问题</title>
    <style>
    </style>
</head>
<body>
    <button>点我发送请求</button>
    <script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');
        let isSending = false; // 标识是否正在发送请求
        let xhr = null;

        btn.addEventListener('click',function(){
            if(isSending == true) xhr.abort();
            xhr = new XMLHttpRequest();
            isSending = true;
            xhr.open('GET','http://127.0.0.1:8000/e');
            xhr.send();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    isSending = false;
                    if(xhr.status >= 200 && xhr.status < 300){
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>
</html>

Formato comum para JQuery enviar ajax

$('button').eq(2).click(function(){
            $.ajax({
                url: "http://127.0.0.1:8000/JQuery",
                type: 'GET',
                timeout: 5000,
                // data: {
                //     "username": username,
                //     "password": passerword,
                // },
                dataType: "text",
                success: function(data){
                    alert("请求成功");
                    console.log(data);
                },
                error: function(){
                    alert("请求失败");
                }
            })
        })

Formato comum para axios enviarem requisições

btns[2].onclick = function(){
            axios({
                method: 'POST',
                // url
                url: 'http:// 127.0.0.1:8080/axios-server',
                // url参数
                params: {
                    vip:10,
                    level:30,
                },
                // 请求体参数
                data: {
                    username:'admin',
                    password: 'admin'
                }
            })
        }

Solução oficial entre domínios

 

Acho que você gosta

Origin blog.csdn.net/qq_61567032/article/details/126337814
Recomendado
Clasificación