• 20231109-【尚硅谷】3小时Ajax入门到精通学习笔记


    1、安装NodeJS

    官网链接】安装一直点下一步就行了

    验证是否安装成功:
    ① win + r,输入cmd
    ② 输入:node -v
    ③ 如果出现版本号,说明安装成功

    2、Express框架

    ① 在项目目录中打开了命令行终端,输入:npm init --yes(用于快速创建一个 Node.js 项目的 package.json 文件,并将所有选项设置为默认值。)
    ② 安装Express框架:npm i express
    ③ 编写代码:

    // 1、引入Express
    const express = require("express");
    
    // 2、创建应用对象
    const app = express();
    
    // 3、创建路由规则
    // request 是对请求报文的封装
    // response 是对响应报文的封装
    app.all('/', (request, response) => {
      // 设置响应头 设置允许跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
    
      // 服务器允许浏览器发送任意的请求头信息
      response.setHeader("Access-Control-Allow-Headers", "*");
     
      // 服务器允许所有请求方法
      response.setHeader("Access-Control-Allow-Method", "*");
       
      // 设置响应体
      response.send("HELLO EXPRESS!");
    });
    
    // 4、监听端口启动服务
    app.listen(8000, () => {
      console.log("服务已启动,8000 端口监听中....")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    ④ 运行服务,在终端输入:node 脚本名
    ⑤ 关闭服务:Ctrl + C

    AJAX发送GET请求

    客户端代码

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>AJAX发送GET请求title>
      <style>
        .box {
          width: 640px;
          height: 480px;
          margin: 200px auto;
          border: 1px solid black;
          position: relative;
          text-align: center;
        }
    
        .btn {
          width: 120px;
          height: 40px;
          background-color: blueviolet;
          color: white;
          font-size: 14px;
          border-radius: 10px;
          margin-top: 50px;
        }
    
        #result {
          width: 320px;
          height: 240px;
          border: 3px solid slateblue;
          position: absolute;
          left: 50%;
          top: 60%;
          transform: translate(-50%, -50%);
        }
      style>
    head>
    
    <body>
      <div class="box">
        <button class="btn">发送GET请求button>
        <div id="result">div>
      div>
    
      <script>
        const btn = document.getElementsByClassName("btn")[0];
        const result = document.getElementById("result");
        btn.onclick = function () {
          console.log("Click!");
    
          // 1、创建对象
          const xhr = new XMLHttpRequest();
    
          // 2、初始化 设置请求方法和URL
          // 如需设置参数,直接在url后面加?a=100&b=200&c=300
          xhr.open("GET", "http://127.0.0.1:8000/server");
    
          // 3、发送
          xhr.send();
    
          // 4、事件绑定 处理服务端返回的结果
          // readystate 是 xhr 对象中的属性
          // 表示状态 0(未初始化) 1(执行完open方法) 2(执行完send方法) 3(服务端返回部分结果) 4(服务端返回全部结果)
          xhr.onreadystatechange = function () {
            // 判断(服务端返回了所有的结果)
            if (xhr.readyState === 4) {
              // 判断响应状态码
              // 200 OK:请求成功。服务器成功处理了请求并返回所请求的资源。
              // 201 Created:已创建。请求成功,并且服务器已经创建了新的资源。
              // 204 No Content:无内容。服务器成功处理了请求,但没有返回任何内容。
              // 400 Bad Request:请求错误。服务器无法理解或处理请求的语法。
              // 401 Unauthorized:未授权。请求要求身份验证,但用户未提供有效的身份凭据。
              // 403 Forbidden:禁止访问。服务器拒绝请求访问资源,没有权限。
              // 404 Not Found:未找到。服务器找不到请求的资源。
              // 500 Internal Server Error:服务器内部错误。服务器在处理请求过程中发生了错误。
              // 502 Bad Gateway:错误的网关。作为网关或代理服务器的服务器,从上游服务器接收到无效的响应。
              // 503 Service Unavailable:服务不可用。服务器暂时过载或维护,无法处理请求。
              if (xhr.status === 200) {
                // 处理结果 行 头 空行 体
                console.log(xhr.status); // 状态码
                console.log(xhr.statusText); // 状态字符串
                console.log(xhr.getAllResponseHeaders); // 所有响应头
                console.log(xhr.response); // 响应体
    
                result.innerHTML = xhr.response;
              } else {
                console.log("请求失败...");
              }
            }
          }
        }
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96

    服务端代码

    // 1、引入Express
    const express = require("express");
    
    // 2、创建应用对象
    const app = express();
    
    // 3、创建路由规则
    // request 是对请求报文的封装
    // response 是对响应报文的封装
    app.get('/server', (request, response) => {
      // 设置响应头 设置允许跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
    
      // 服务器允许浏览器发送任意的请求头信息
      response.setHeader("Access-Control-Allow-Headers", "*");
     
      response.setHeader("Access-Control-Allow-Method", "*");
    
      // 设置响应体
      response.send("HELLO AJAX!");
    });
    
    // 4、监听端口启动服务
    app.listen(8000, () => {
      console.log("服务已启动,8000 端口监听中....")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    AJAX发送POST请求

    客户端代码

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>AJAX发送POST请求title>
      <style>
        .box {
          width: 640px;
          height: 480px;
          margin: 200px auto;
          border: 1px solid black;
          position: relative;
          text-align: center;
        }
    
        .btn {
          width: 120px;
          height: 40px;
          background-color: blueviolet;
          color: white;
          font-size: 14px;
          border-radius: 10px;
          margin-top: 50px;
        }
    
        #result {
          width: 320px;
          height: 240px;
          border: 3px solid slateblue;
          position: absolute;
          left: 50%;
          top: 60%;
          transform: translate(-50%, -50%);
        }
      style>
    head>
    
    <body>
      <div class="box">
        <button class="btn">发送POST请求button>
        <div id="result">div>
      div>
    
      <script>
        const btn = document.getElementsByClassName("btn")[0];
        const result = document.getElementById("result");
        btn.addEventListener("click", function () {
          console.log("Click!");
    
          // 1、创建对象
          const xhr = new XMLHttpRequest();
    
          // 2、初始化 设置请求方法和URL
          // 如需设置参数,直接在url后面加?a=100&b=200&c=300
          xhr.open("POST", "http://127.0.0.1:8000/server");
    
          // 3、发送
          // xhr.send();
          xhr.send("a=100&b=200&c=300"); // 传递参数
    
          // 4、事件绑定 处理服务端返回的结果
          xhr.onreadystatechange = function () {
            // 判断(服务端返回了所有的结果)
            if (xhr.readyState === 4) {
              // 判断响应状态码
              if (xhr.status >= 200 && xhr.status < 300) {
                // 处理结果 行 头 空行 体
                result.innerHTML = xhr.response;
              } else {
                console.log("请求失败...");
              }
            }
          }
        });
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80

    服务端代码

    // 1、引入Express
    const express = require("express");
    
    // 2、创建应用对象
    const app = express();
    
    // 3、创建路由规则
    // request 是对请求报文的封装
    // response 是对响应报文的封装
    app.post('/server', (request, response) => {
      // 设置响应头 设置允许跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
    
      // 服务器允许浏览器发送任意的请求头信息
      response.setHeader("Access-Control-Allow-Headers", "*");
     
      response.setHeader("Access-Control-Allow-Method", "*");
    
      // 设置响应体
      response.send("HELLO AJAX POST!");
    });
    
    // 4、监听端口启动服务
    app.listen(8000, () => {
      console.log("服务已启动,8000 端口监听中....")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    设置请求头信息

    // 1、创建对象
    const xhr = new XMLHttpRequest();
    
    // 2、初始化 设置请求方法和URL
    // 如需设置参数,直接在url后面加?a=100&b=200&c=300
    xhr.open("POST", "http://127.0.0.1:8000/server");
    
    // 3、设置请求头
    xhr.setRequestHeader('name', 'ajax'); // 自定义请求头
    
    // 4、发送
    // xhr.send();
    xhr.send("a=100&b=200&c=300"); // 传递参数
    
    // 5、事件绑定 处理服务端返回的结果
    xhr.onreadystatechange = function () {
      // 判断(服务端返回了所有的结果)
      if (xhr.readyState === 4) {
        // 判断响应状态码
        if (xhr.status >= 200 && xhr.status < 300) {
          // 处理结果 行 头 空行 体
          result.innerHTML = xhr.response;
        } else {
          console.log("请求失败...");
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    服务端响应JSON数据

    客户端代码

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>服务端响应JSON数据title>
      <style>
        .box {
          width: 640px;
          height: 480px;
          margin: 200px auto;
          border: 1px solid black;
          position: relative;
          text-align: center;
        }
    
        .btn {
          width: 120px;
          height: 40px;
          background-color: blueviolet;
          color: white;
          font-size: 14px;
          border-radius: 10px;
          margin-top: 50px;
        }
    
        #result {
          width: 320px;
          height: 240px;
          border: 3px solid slateblue;
          position: absolute;
          left: 50%;
          top: 60%;
          transform: translate(-50%, -50%);
        }
      style>
    head>
    
    <body>
      <div class="box">
        <button class="btn">发送请求button>
        <div id="result">div>
      div>
    
      <script>
        const btn = document.getElementsByClassName("btn")[0];
        const result = document.getElementById("result");
        btn.addEventListener("click", function () {
          console.log("Click!");
    
          // 1、创建对象
          const xhr = new XMLHttpRequest();
    
          // 设置响应体数据类型
          // xhr.responseType = 'json';
    
          // 2、初始化 设置请求方法和URL
          // 如需设置参数,直接在url后面加?a=100&b=200&c=300
          xhr.open("GET", "http://127.0.0.1:8000/server");
    
          // 3、设置请求头
          // xhr.setRequestHeader('name', 'ajax'); // 自定义请求头
    
          // 4、发送
          xhr.send();
    
          // 5、事件绑定 处理服务端返回的结果
          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 + " 性别:" + data.sex + " 年龄:" + data.age;
    
                // 自动转换 就设置响应体数据的类型
                // result.innerHTML = "姓名:" + xhr.response.name + " 性别:" + xhr.response.sex + " 年龄:" + xhr.response.age;
              } else {
                console.log("请求失败...");
              }
            }
          }
        });
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90

    服务端代码

    // 1、引入Express
    const express = require("express");
    
    // 2、创建应用对象
    const app = express();
    
    // 3、创建路由规则
    // request 是对请求报文的封装
    // response 是对响应报文的封装
    app.all('/server', (request, response) => {
      // 设置响应头 设置允许跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
    
      // 服务器允许浏览器发送任意的请求头信息
      response.setHeader("Access-Control-Allow-Headers", "*");
     
      response.setHeader("Access-Control-Allow-Method", "*");
    
      const data = {
        name: "张三",
        sex: "男",
        age: "18"
      }
    
      // 对对象进行字符串转换
      let str = JSON.stringify(data);
    
      // 设置响应体
      response.send(str);
    });
    
    // 4、监听端口启动服务
    app.listen(8000, () => {
      console.log("服务已启动,8000 端口监听中....")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    安装自动重启服务端工具

    npm install -g nodemon
    启动服务:nodemon 脚本名
    如果出现 “因为在此系统上禁止运行脚本”,请按以下步骤解决此问题:
    ① 搜索Windows PowerShell,右键选择以管理员身份运行
    ② 输入:set-ExecutionPolicy RemoteSigned
    ③ 选择Y 或者 A ,就好了

    解决IE缓存问题

    在链接后面加上:‘http://127.0.0.1:8000?t=’ + Date.now(); 即可

    请求超时与网络异常(xhr.timeout = 2000;)

    客户端

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>请求超时与网络异常title>
      <style>
        .box {
          width: 640px;
          height: 480px;
          margin: 200px auto;
          border: 1px solid black;
          position: relative;
          text-align: center;
        }
    
        .btn {
          width: 120px;
          height: 40px;
          background-color: blueviolet;
          color: white;
          font-size: 14px;
          border-radius: 10px;
          margin-top: 50px;
        }
    
        #result {
          width: 320px;
          height: 240px;
          border: 3px solid slateblue;
          position: absolute;
          left: 50%;
          top: 60%;
          transform: translate(-50%, -50%);
        }
      style>
    head>
    
    <body>
      <div class="box">
        <button class="btn">发送GET请求button>
        <div id="result">div>
      div>
    
      <script>
        const btn = document.getElementsByClassName("btn")[0];
        const result = document.getElementById("result");
        btn.addEventListener('click', function () {
          console.log("Click!");
    
          // 创建对象
          const xhr = new XMLHttpRequest();
    
          // 超时设置 2s
          xhr.timeout = 2000;
    
          // 超时回调
          xhr.ontimeout = function () {
            alert("网络异常,请稍后重试!!!");
          }
          
          // 网络异常回调
          xhr.onerror = function () {
            alert("你的网络似乎出了一些问题!!!");
          }
    
          // 初始化 设置请求方法和URL
          // 如需设置参数,直接在url后面加?a=100&b=200&c=300
          xhr.open("GET", "http://127.0.0.1:8000/server");
    
          // 发送
          xhr.send();
    
          // 事件绑定 处理服务端返回的结果
          xhr.onreadystatechange = function () {
            // 判断(服务端返回了所有的结果)
            if (xhr.readyState === 4) {
              // 判断响应状态码
              if (xhr.status === 200) {
                // 处理结果
    
                result.innerHTML = xhr.response;
              } else {
                console.log("请求失败...");
              }
            }
          }
        });
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93

    服务端

    // 1、引入Express
    const express = require("express");
    
    // 2、创建应用对象
    const app = express();
    
    // 3、创建路由规则
    // request 是对请求报文的封装
    // response 是对响应报文的封装
    app.all('/server', (request, response) => {
      // 设置响应头 设置允许跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
    
      // 服务器允许浏览器发送任意的请求头信息
      response.setHeader("Access-Control-Allow-Headers", "*");
      
      response.setHeader("Access-Control-Allow-Method", "*");
    
      setTimeout(() => {
        // 设置响应体
        response.send("延迟响应...");
      }, 3000);
    
    });
    
    // 4、监听端口启动服务
    app.listen(8000, () => {
      console.log("服务已启动,8000 端口监听中....")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    取消请求(xhr.about();)

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>取消请求title>
      <style>
        .box {
          width: 640px;
          height: 480px;
          margin: 200px auto;
          border: 1px solid black;
          position: relative;
          text-align: center;
        }
    
        .btn {
          width: 120px;
          height: 40px;
          background-color: blueviolet;
          color: white;
          font-size: 14px;
          border-radius: 10px;
          margin-top: 50px;
        }
    
        #result {
          width: 320px;
          height: 240px;
          border: 3px solid slateblue;
          position: absolute;
          left: 50%;
          top: 60%;
          transform: translate(-50%, -50%);
        }
      style>
    head>
    
    <body>
      <div class="box">
        <button class="btn" id="sendBtn">发送请求button>
        <button class="btn" id="cancelBtn">取消请求button>
        <div id="result">div>
      div>
    
      <script>
        const sendBtn = document.getElementById("sendBtn");
        const cancelBtn = document.getElementById("cancelBtn");
        const result = document.getElementById("result");
        let xhr = null;
        sendBtn.addEventListener('click', function () {
    
          console.log("SendButtonOnClick!");
    
          // 创建对象
          xhr = new XMLHttpRequest();
    
          // 超时设置 6s
          xhr.timeout = 6000;
    
          // 超时回调
          xhr.ontimeout = function () {
            alert("网络异常,请稍后重试!!!");
          }
    
          // 网络异常回调
          xhr.onerror = function () {
            alert("你的网络似乎出了一些问题!!!");
          }
    
          // 初始化 设置请求方法和URL
          // 如需设置参数,直接在url后面加?a=100&b=200&c=300
          xhr.open("GET", "http://127.0.0.1:8000/server");
    
          // 发送
          xhr.send();
    
          // 事件绑定 处理服务端返回的结果
          xhr.onreadystatechange = function () {
            // 判断(服务端返回了所有的结果)
            if (xhr.readyState === 4) {
              // 判断响应状态码
              if (xhr.status === 200) {
                // 处理结果
    
                result.innerHTML = xhr.response;
              } else {
                console.log("请求失败...");
              }
            }
          }
        });
    
        cancelBtn.addEventListener('click', function () {
          xhr.abort();
          alert("取消请求");
        });
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102

    解决请求重复发送问题

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>请求重复发送问题title>
      <style>
        .box {
          width: 640px;
          height: 480px;
          margin: 200px auto;
          border: 1px solid black;
          position: relative;
          text-align: center;
        }
    
        .btn {
          width: 120px;
          height: 40px;
          background-color: blueviolet;
          color: white;
          font-size: 14px;
          border-radius: 10px;
          margin-top: 50px;
        }
    
        #result {
          width: 320px;
          height: 240px;
          border: 3px solid slateblue;
          position: absolute;
          left: 50%;
          top: 60%;
          transform: translate(-50%, -50%);
        }
      style>
    head>
    
    <body>
      <div class="box">
        <button class="btn" id="sendBtn">发送请求button>
        <button class="btn" id="cancelBtn">取消请求button>
        <div id="result">div>
      div>
    
      <script>
        const sendBtn = document.getElementById("sendBtn");
        const cancelBtn = document.getElementById("cancelBtn");
        const result = document.getElementById("result");
        let xhr = null;
        let isSending = false; // 标识变量 是否正在发送AJAX请求
    
        sendBtn.addEventListener('click', function () {
    
          console.log("SendButtonOnClick!");
    
          // 判断标识变量 如果请求正在发送 则取消该请求 创建一个新的请求
          if (isSending)
            xhr.abort();
    
          // 创建对象
          xhr = new XMLHttpRequest();
    
          isSending = true;
    
          // 超时设置 6s
          xhr.timeout = 6000;
    
          // 超时回调
          xhr.ontimeout = function () {
            alert("网络异常,请稍后重试!!!");
          }
    
          // 网络异常回调
          xhr.onerror = function () {
            alert("你的网络似乎出了一些问题!!!");
          }
    
          // 初始化 设置请求方法和URL
          // 如需设置参数,直接在url后面加?a=100&b=200&c=300
          xhr.open("GET", "http://127.0.0.1:8000/server");
    
          // 发送
          xhr.send();
    
          // 事件绑定 处理服务端返回的结果
          xhr.onreadystatechange = function () {
            // 判断(服务端返回了所有的结果)
            if (xhr.readyState === 4) {
    
              isSending = false;
    
              // 判断响应状态码
              if (xhr.status === 200) {
                // 处理结果
    
                result.innerHTML = xhr.response;
              } else {
                console.log("请求失败...");
              }
            }
          }
        });
    
        cancelBtn.addEventListener('click', function () {
          xhr.abort();
          alert("取消请求");
        });
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113

    jQuery发送AJAX请求

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>jQuery 发送 AJAX 请求title>
      <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js">script>
    head>
    
    <body>
      <button>GETbutton>
      <button>POSTbutton>
      <button>通用型方法button>
    
      <script>
        $('button').eq(0).click(function () {
          //请求链接 请求参数 响应回调
          $.get('http://127.0.0.1:8000/server', { a: 100, b: 100 }, function (data) {
            console.log('GET:' + data);
          });
        });
    
        $('button').eq(1).click(function () {
          //请求链接 请求参数 响应回调 响应类型
          // "xml": 预计服务器返回XML格式的数据。
          // "html": 预计服务器返回HTML格式的数据。
          // "text": 预计服务器返回纯文本数据。
          // "json": 预计服务器返回JSON格式的数据。
          // "jsonp": 预计服务器返回JSONP格式的数据。
          // "script": 预计服务器返回JavaScript代码。
          $.post('http://127.0.0.1:8000/server', { a: 100, b: 100 }, function (data) {
            console.log('POST:' + data);
          }, 'text');
        });
    
        $('button').eq(2).click(function () {
          $.ajax({
            // 请求链接
            url: 'http://127.0.0.1:8000/server',
            // 请求参数
            data: { a: 100, b: 200 },
            // 请求类型
            type: 'GET',
            // 响应体结果类型
            dataType: 'text',
            // 请求成功回调
            success: function (data) {
              console.log('jQurey AJAX:' + data);
            },
            // 超时时间
            timeout: 1000,
            // 失败的回调
            error: function () {
              console.log("出错啦!!!");
            },
            // 头信息
            headers: {
              c: 300,
              d: 400
            }
          })
        });
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    Axios发送AJAX请求

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Axios发送AJAX请求title>
    
      
      <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js">script>
    head>
    
    <body>
      <button>GETbutton>
      <button>POSTbutton>
      <button>AJAXbutton>
    
      <script>
        const btns = document.querySelectorAll('button');
    
        // 配置 baseURL
        axios.defaults.baseURL = "http://127.0.0.1:8000";
    
        btns[0].onclick = function () {
          axios.get('/server', {
            // url 参数
            params: {
              a: 100,
              b: 200
            },
            // 请求头信息
            headers: {
              name: 'KingXy',
              age: 18
            }
          }).then(value => {
            console.log(value);
          })
        }
    
        btns[1].onclick = function () {
          axios.post('/server',
            // 请求体
            {
              username: "zhangsan",
              password: "admin"
            },
            {
              // url 参数
              params: {
                a: 100,
                b: 200
              },
              // 请求头信息
              headers: {
                name: 'KingXy',
                age: 18
              }
            }).then(value => {
              console.log(value);
            })
        }
    
        btns[2].onclick = function () {
          axios({
            // 请求方法
            method: 'POST',
            url: '/server',
            // url 参数
            params: {
              a: 100,
              b: 200
            },
            // 头信息
            headers: {
              c: 300,
              d: 400
            },
            // 请求体参数
            data: {
              username: "admin",
              password: 'admin'
            }
          })
        }
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89

    使用fetch函数发送AJAX请求

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>使用fetch函数发送AJAX请求title>
    head>
    
    <body>
      <button>AJAX请求button>
      <script>
        const btn = document.querySelector('button');
        btn.onclick = function () {
          fetch('http://127.0.0.1:8000/server?vip=me', {
            method: 'POST',
            headers: {
              name: "ZhangSan"
            },
            body: 'username=admin&password=admin'
          }).then(response => {
            return response.text();
            // return response.json();
          }).then(response => {
            console.log(response);
          })
        }
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    原生JSONP

    客户端

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>JSONP实践title>
    head>
    
    <body>
      用户名:<input type="text" id="username">
      <p>p>
      <script>
        const input = document.querySelector('input');
        const p = document.querySelector('p');
    
        function handle(data) {
          input.style.border = '1px solid #f00';
          p.innerHTML = data.msg;
        }
    
        // 绑定输入框失去焦点事件
        input.onblur = function () {
          // 获取用户的输入值
          let username = this.value;
          // 创建script标签
          const script = document.createElement('script');
          // 设置标签的src属性
          script.src = 'http://127.0.0.1:8000/server';
          // 将script插入到文档中
          document.body.append(script);
        }
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    服务端

    // 1、引入Express
    const express = require("express");
    
    // 2、创建应用对象
    const app = express();
    
    // 3、创建路由规则
    // request 是对请求报文的封装
    // response 是对响应报文的封装
    app.all('/server', (request, response) => {
      // 设置响应头 设置允许跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
    
      // 服务器允许浏览器发送任意的请求头信息
      response.setHeader("Access-Control-Allow-Headers", "*");
    
      response.setHeader("Access-Control-Allow-Method", "*");
     
      const data = {
        exist: 1,
        msg: '用户名已经存在'
      }
    
      let str = JSON.stringify(data);
    
      // 设置响应体
      response.send(`handle(${str})`);
    });
    
    // 4、监听端口启动服务
    app.listen(8000, () => {
      console.log("服务已启动,8000 端口监听中....")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    jQuery发送JSONP请求

    客户端

    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>jQuery 发送 jsonp请求title>
      <style>
        #result {
          width: 160px;
          height: 120px;
          border: 1px solid black;
        }
      style>
      <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js">script>
    head>
    
    <body>
      <button>发送button>
      <div id="result">
    
      div>
    
      <script>
        $('button').eq(0).click(function () {
          $.getJSON('http://127.0.0.1:8000/server?callback=?', function (data) {
            console.log(data);
            $('#result').html(`
            姓名:${data.name}
            
    爱好:
    ${data.hobby} `
    ); }); });
    script> body> html>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    服务端

    // 1、引入Express
    const express = require("express");
    
    // 2、创建应用对象
    const app = express();
    
    // 3、创建路由规则
    // request 是对请求报文的封装
    // response 是对响应报文的封装
    app.all('/server', (request, response) => {
      // 设置响应头 设置允许跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
    
      // 服务器允许浏览器发送任意的请求头信息
      response.setHeader("Access-Control-Allow-Headers", "*");
    
      response.setHeader("Access-Control-Allow-Method", "*");
    
      const data = {
        name: '张三',
        hobby: '打篮球'
      }
    
      let str = JSON.stringify(data);
    
      // 接收callback参数
      let cb = request.query.callback;
    
      // 设置响应体
      response.send(`${cb}(${str})`);
    });
    
    // 4、监听端口启动服务
    app.listen(8000, () => {
      console.log("服务已启动,8000 端口监听中....")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    LVS-dr模式部署
    分享一下怎么做陪诊小程序
    C语言自定义类型讲解:结构体,枚举,联合(2)
    Jmeter —— jmeter参数化实现
    python学习笔记(05)---(内置容器-列表)
    用DIV+CSS技术设计的公益主题网站——防止电信诈骗(web前端网页制作课作业)
    Jdk 1.8 for mac 详细安装教程(含版本切换)
    Design Pattern (GoF)
    Linux之慢盘检测
    c++并发编程/多线程 thread 库
  • 原文地址:https://blog.csdn.net/qq_44887198/article/details/134308086