• AJAX到AXIOS常用格式汇总


    HTTP协议

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

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

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

    node.js下载地址:Node.js

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

    发送GET请求的基本格式

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

    在url里面设置参数

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

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

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

    一般情况下还要设置跨域

    发送POST请求的基本格式

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>POST 请求title>
    8. <style>
    9. #result{
    10. width: 200px;
    11. height: 200px;
    12. border: 1px solid #903;
    13. }
    14. style>
    15. head>
    16. <body>
    17. <div id="result">
    18. div>
    19. <script>
    20. // 获取元素
    21. const result = document.getElementById('result');
    22. // 绑定事件
    23. result.addEventListener('mouseover',function(){
    24. // 创建对象
    25. const xhr = new XMLHttpRequest();
    26. // 初始化 设置请求类型和url】
    27. xhr.open('POST','http://127.0.0.1:8000');
    28. // 发送
    29. xhr.send('a=100&b=200&c=300');
    30. // 事件绑定
    31. xhr.onreadystatechange = function(){
    32. // 判断状态
    33. if(xhr.readyState === 4){
    34. if(xhr.status >= 200 && xhr.status < 300){
    35. // 处理返回结果
    36. result.innerHTML = xhr.response;
    37. }
    38. }
    39. }
    40. })
    41. script>
    42. body>
    43. html>

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

    需要写在send的括号里面

    上述三种均可

    json数据响应式处理

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

    {'name':'ayguigfu'};
    

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

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>3-jsontitle>
    8. <style>
    9. #result{
    10. width: 200px;
    11. height: 100px;
    12. border: 1px solid #903;
    13. }
    14. style>
    15. head>
    16. <body>
    17. <div id="result">div>
    18. <script>
    19. const result = document.getElementById('result');
    20. window.onkeydown = function(){
    21. // 创建对象
    22. const xhr = new XMLHttpRequest();
    23. // 自动转换数据需要的设置响应数据的类型
    24. xhr.responseType = 'json';
    25. // 初始化
    26. xhr.open('GET','http://127.0.0.1:8000/json-server');
    27. // 发送
    28. xhr.send();
    29. // 事件绑定
    30. xhr.onreadystatechange = function(){
    31. if(xhr.readyState === 4){
    32. if(xhr.status >= 200 && xhr.status < 300){
    33. // 手动对数据做一个转换
    34. // let data = JSON.parse(xhr.response);
    35. // console.log(data);
    36. // result.innerHTML = data.name;
    37. // console.log(xhr.response);
    38. result.innerHTML = xhr.response.name;
    39. }
    40. }
    41. }
    42. }
    43. script>
    44. body>
    45. html>

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

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

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

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

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>网络超时和异常title>
    8. <style>
    9. #result{
    10. width: 200px;
    11. height: 200px;
    12. border: 1px solid #394;
    13. }
    14. style>
    15. head>
    16. <body>
    17. <button>点我发送请求button>
    18. <div id="result">div>
    19. <script>
    20. const btn = document.getElementsByTagName('button')[0];
    21. const result = document.getElementById('result');
    22. btn.addEventListener('click',function(){
    23. const xhr = new XMLHttpRequest();
    24. // 请求超时设置 2s
    25. xhr.timeout = 2000;
    26. // 超时回调
    27. xhr.ontimeout = function(){
    28. alert('网络异常,请稍后重试');
    29. }
    30. // 网络异常回调
    31. xhr.onerror = function(){
    32. alert('您的网络似乎出了一点问题');
    33. }
    34. xhr.open('GET','http://127.0.0.1:8000/e');
    35. xhr.send();
    36. xhr.onreadystatechange = function(){
    37. if(xhr.readyState === 4){
    38. if(xhr.status >= 200 && xhr.status < 300){
    39. result.innerHTML = xhr.response;
    40. }
    41. }
    42. }
    43. })
    44. script>
    45. body>
    46. html>

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

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

    手动取消请求

    重复请求问题

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

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>重复请求问题title>
    8. <style>
    9. style>
    10. head>
    11. <body>
    12. <button>点我发送请求button>
    13. <script>
    14. const btn = document.getElementsByTagName('button')[0];
    15. const result = document.getElementById('result');
    16. let isSending = false; // 标识是否正在发送请求
    17. let xhr = null;
    18. btn.addEventListener('click',function(){
    19. if(isSending == true) xhr.abort();
    20. xhr = new XMLHttpRequest();
    21. isSending = true;
    22. xhr.open('GET','http://127.0.0.1:8000/e');
    23. xhr.send();
    24. xhr.onreadystatechange = function(){
    25. if(xhr.readyState === 4){
    26. isSending = false;
    27. if(xhr.status >= 200 && xhr.status < 300){
    28. result.innerHTML = xhr.response;
    29. }
    30. }
    31. }
    32. })
    33. script>
    34. body>
    35. html>

    JQuery发送请求

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

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>重复请求问题title>
    8. <style>
    9. style>
    10. head>
    11. <body>
    12. <button>点我发送请求button>
    13. <script>
    14. const btn = document.getElementsByTagName('button')[0];
    15. const result = document.getElementById('result');
    16. let isSending = false; // 标识是否正在发送请求
    17. let xhr = null;
    18. btn.addEventListener('click',function(){
    19. if(isSending == true) xhr.abort();
    20. xhr = new XMLHttpRequest();
    21. isSending = true;
    22. xhr.open('GET','http://127.0.0.1:8000/e');
    23. xhr.send();
    24. xhr.onreadystatechange = function(){
    25. if(xhr.readyState === 4){
    26. isSending = false;
    27. if(xhr.status >= 200 && xhr.status < 300){
    28. result.innerHTML = xhr.response;
    29. }
    30. }
    31. }
    32. })
    33. script>
    34. body>
    35. html>

    JQuery发送ajax的通用格式

    1. $('button').eq(2).click(function(){
    2. $.ajax({
    3. url: "http://127.0.0.1:8000/JQuery",
    4. type: 'GET',
    5. timeout: 5000,
    6. // data: {
    7. // "username": username,
    8. // "password": passerword,
    9. // },
    10. dataType: "text",
    11. success: function(data){
    12. alert("请求成功");
    13. console.log(data);
    14. },
    15. error: function(){
    16. alert("请求失败");
    17. }
    18. })
    19. })

    axios发送请求的通用格式

    1. btns[2].onclick = function(){
    2. axios({
    3. method: 'POST',
    4. // url
    5. url: 'http:// 127.0.0.1:8080/axios-server',
    6. // url参数
    7. params: {
    8. vip:10,
    9. level:30,
    10. },
    11. // 请求体参数
    12. data: {
    13. username:'admin',
    14. password: 'admin'
    15. }
    16. })
    17. }

    官方跨域解决方案

     

  • 相关阅读:
    转载——比较器的原理
    RHCE(三、四)NTP时间服务器、SSH远程加密登录
    express session JWT JSON Web Token
    java-net-php-python-11jspm健身管理网站计算机毕业设计程序
    C语言每日一练——Day01:求最大公约数(三种方法)
    GLM-4-9B 支持 Ollama 部署
    python解析.hhr文件
    如何把握好Shopee节日大促?Shopee77大促营销策略
    刀具磨损状态识别(Python代码,MSCNN_LSTM_Attention模型,初期磨损、正常磨损和急剧磨损分类,解压缩直接运行)
    开源之夏2023 MatrixOne 项目结业啦
  • 原文地址:https://blog.csdn.net/qq_61567032/article/details/126337814