• 初学原生Ajax-补充:原生ajax的封装使用


    原生ajax的封装使用

    我们先准备一个服务器

    • server.js
    const express = require("express")
    
    const app = express()
    
    app.get("/user",(req,res)=>{
        // res.setHeader("Access-Control-Allow-Methods","*")
        res.setHeader('Access-Control-Allow-Origin','*')
        console.log("服务器收到请求");
        res.send({"name":"hello","age":20})
    
    })
    
    app.listen(8080,()=>{
        console.log("服务器启动,监听8080端口!");
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    启动服务器:node server.js

    最基本的封装

    <div>
       <button onclick="sendMessage()">发送请求button>
    div>
    <script>
       // 点击触发sendMessage()方法
       function sendMessage(){
           // 调用封装的ajax方法,传入url,回调函数
           getData("http://localhost:8080/user",(res)=>{
               console.log(res);
           })
       }
    
       /**
       	* @function 封装ajax
        * @url:请求的url地址
        * @callback,请求成功后的回调函数
        */
       function getData(url,callback){
           let xhr = new XMLHttpRequest()
           xhr.open("get",url)
           xhr.send()
           xhr.responseType = "json" // 返回response对象
           xhr.onreadystatechange = function(){
               if(this.readyState === 4 && this.status === 200){
                   // console.log(xhr.response);
                   callback(xhr.response) // 回调函数
               }
           }
       }
    script>
    
    • 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

    ES6中的promise函数封装

    • 纯pormise实现
    <script>
      // 点击触发sendMessage()方法
      function sendMessage() {
        // 调用封装的ajax方法,传入url,回调函数
        getData("http://localhost:8080/user", (res) => {
          console.log(res);
        });
      }
    
      /**
       * @url:请求的url地址
       * @callback,请求成功后的回调函数
       */
      function getData(url, callback) {
        const p = new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          xhr.open("get", url);
          xhr.send();
          xhr.responseType = "json"; // 返回response对象
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 300) {
                // 成功则获取响应体
                resolve(xhr.response);
              } else {
                // 失败就返回状态码
                reject(xhr.status);
              }
            }
          };
        });
    
        p.then(
          function (value) {
            callback(value); // value就是xhr.response
          },
          function (err) {
            console.log(err);
          }
        );
      }
    script>
    
    • 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
    • promise+async+await实现
    <div>
      <button onclick="sendMessage()">发送请求button>
    div>
    <script>
      // 点击触发sendMessage()方法
      async function sendMessage() {
        // 调用封装的ajax方法,传入url,回调函数
        let result = await getData("http://localhost:8080/user");
        console.log(result);
      }
    
      /**
       * @url:请求的url地址
       */
      function getData(url) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          xhr.open("get", url);
          xhr.send();
          xhr.responseType = "json"; // 返回response对象
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 300) {
                // 成功则获取响应体
                resolve(xhr.response);
              } else {
                // 失败就返回状态码
                reject(xhr.status);
              }
            }
          };
        });
      }
    script>
    
    • 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
  • 相关阅读:
    Git clone时报错: OpenSSL SSL_read: Connection was reset, errno 10054
    纯js实现html指定页面导出word
    PyQt5+Qt设计师初探
    对硬件编程的一点理解---vitis使用
    哪些活动适合媒体邀约?有啥作用
    广义回归神经网络的应用,广义回归神经网络原理
    秋招每日一题T25——最少交换次数
    一个用C#开发的操作系统的开源项目
    修改Qt源码支持DPI粒度到QWidget
    49 二叉树的最近公共祖先
  • 原文地址:https://blog.csdn.net/lalala_dxf/article/details/128023459