AJAX到AXIOS常用格式汇总

HTTP协议

  • 协议详细规定了浏览器和万维网服务器之间相互通信的规则
  • 浏览器给服务器发送,成为请求,发送的内容成为请求报文
    • 请求格式
行 : 包含:请求类型(GET、POST等)、url路径、HTTP版本
头	: 包含很多内容,固定格式是:[名字][英文冒号][空格][体]
空行
请求体:如果是GET请求,此处为空; 如果是POST请求,此处可以不为空

  • 服务器给浏览器结果,成为响应,结果的内容成为响应报文
    • 响应报文的格式
行:包含:HTTP协议版本、响应状态码(200表示成功,404表示找不到网页)、响应状态字符串
头:格式跟请求头一样
空行
体:主要的返回内容,可以是html格式的

一般使用和演示ajax需要下载node.js和使用express框架(作为我们的前端)

node.js下载地址:Node.js

express网址:Express - 基于 Node.js 平台的 web 应用开发框架 - Express 中文文档 | Express 中文网

发送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>

在url里面设置参数

  • 用?连接地址和参数列表
  • 同&连接参数列表的多个参数
  • 例如我需要传递a=100;b=200;c=300这三个参数,url的书写:
  • https://www.baidu.com?a=100&b=200&c=300

ajax中引用express框架的基本格式

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

一般情况下还要设置跨域

发送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>

POST设置参数的格式比较灵活,但是在服务端一定要与之对应的处理方式

需要写在send的括号里面

上述三种均可

json数据响应式处理

在开发中,我们常常会遇到像

{'name':'ayguigfu'};

这样的数据,它就是一个对象!但是处理起来很不方便。

<!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>

在server.js文件里面我们设置了专门的路径和响应数据

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);
});

网络超时和网络异常的处理

因为各种各样的原因,我们的请求总是会遇到问题,为了用户的体验,我们不能不管

<!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>

再server.js里面我们写一个单独的规则

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

手动取消请求

重复请求问题

同一个用户和不同的用户之前,可能不停的重复发送同样的请求,这样对我们的服务器很不友好

<!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>

JQuery发送请求

相比于原生ajax请求,JQuery封装的方法会更加方便

<!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>

JQuery发送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("请求失败");
                }
            })
        })

axios发送请求的通用格式

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'
                }
            })
        }

官方跨域解决方案

猜你喜欢

转载自blog.csdn.net/qq_61567032/article/details/126337814