JavaScript-XHR-深入理解

news2025/2/24 3:32:29

JavaScript-XHR-深入理解

  • 1. XHR(Asynchronous JavaScript And XML)初始
    • 1.1. xhr request demo
    • 1.2. status of XHRHttpRequest
    • 1.3. send synchronous request by xhr
    • 1.4. onload监听数据加载完成
    • 1.5. http status code
    • 1.6. get/post request with josn/form/urlcoded
    • 1.7. encapsulate an ajax function to send requests
    • 1.8. encapsulate an ajax function to send requests with Promise
  • 2. Fetch
    • 2.1. fetch demo

1. XHR(Asynchronous JavaScript And XML)初始

1.1. xhr request demo

  • 第一步:创建网络请求的AJAX 对象(使用 XMLHttpRequest
  • 第二步:监听XMLHttpRequest 对象状态的变化,或者监听 onload 事件(请求完成时触发);
  • 第三步:配置网络请求(通过open 方法);
  • 第四步:发送send 网络请求;
<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor the change of status (macrotask)
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) return

            // get the response data
            const resJSON = JSON.parse(xhr.response)
            console.log('response: ', resJSON)
            // data = resJSON
            dataInput.value = JSON.stringify(resJSON)
        }

        // 2. configure request open
        xhr.open('get', 'http://123.xxx:8000/home/multidata')

        // 4. send request
        xhr.send()
    }

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

1.2. status of XHRHttpRequest

Y
在这里插入图片描述
在这里插入图片描述

1.3. send synchronous request by xhr

<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor the change of status (macrotask)
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE) {
              console.log(xhr.readyState)
              return
            }

            // get the response data
            const resJSON = JSON.parse(xhr.response)
            console.log('response: ', resJSON)
            console.log('status: ', xhr.status)
            console.log('xhr: ', xhr)
            // data = resJSON
            dataInput.value = JSON.stringify(resJSON)
        }

        // 2. configure request open
        xhr.open('get', 'http://xxxx.32:8000/home/multidata', true)

        // 4. send request
        xhr.send()

        console.log('here is the log after sending')
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

在这里插入图片描述

        // 2. configure request open
        xhr.open('get', 'http://123.207.32.32:8000/home/multidata', false)

在这里插入图片描述

1.4. onload监听数据加载完成

<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor onload event
        xhr.onload = () => {
            console.log('onload')
            dataInput.value = xhr.response
        }

        // 2. configure request open
        xhr.open('get', 'http://xxx.32:8000/home/multidata', false)

        // 4. send request
        xhr.send()
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

1.5. http status code

<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")
    // debugger
    buttonData.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor onload event
        xhr.onload = () => {
            console.log(xhr.status, xhr.statusText)
            // make a judgement based on http status code
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log('get response success: ', xhr.response)
            } else {
              console.log(xhr.status, xhr.statusText)
            }
            dataInput.value = xhr.response
        }

        xhr.onerror = () => {
          console.log('send request error: ', xhr.status, xhr.statusText)
        }

        // 2. configure request open
        xhr.open('get', 'http://xxx.32:8000/home/mudltidata', false)

        // 4. send request
        xhr.send()
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

在这里插入图片描述

1.6. get/post request with josn/form/urlcoded

<!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>JS-learn</title>
</head>
<body>
    <button class="dataClick">get data</button>
    <button class="clearClick">clear</button>
    <p></p>
    <textarea class="dataArea"></textarea>
    <form class="info">
      <input type="text" name="username">
      <input type="password" name="password">
    </form>
    <p></p>
    <button class="send">send request</button>
  
  <script>

    const buttonData = document.querySelector(".dataClick");
    const dataInput = document.querySelector(".dataArea")
    const clearData =  document.querySelector(".clearClick")


    const formEl = document.querySelector(".info")
    const sendBtn = document.querySelector(".send")
    // debugger
    sendBtn.onclick = function getData(){
        // 1. create XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. monitor onload event
        xhr.onload = () => {
            console.log(xhr.status, xhr.statusText)
            // make a judgement based on http status code
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log('get response success: ', xhr.response)
            } else {
              console.log(xhr.status, xhr.statusText)
            }
            dataInput.value = xhr.response
        }

        xhr.onerror = () => {
          console.log('send request error: ', xhr.status, xhr.statusText)
        }

        // 2. configure request open
        // 2.1. http get
        // xhr.open('get', 'http://xxx.32:1888/02_param/get?name=michael&age=18&address=广州市')
        // xhr.send()

        // 2.2. post: urlencoded
        // xhr.open('post', 'http://xxx.32:1888/02_param/posturl')
        // xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
        // xhr.send('name=michael&age=18&address=广州市')

        // 2.3. post: formdata
        // xhr.open('post', 'http://xxx.32:1888/02_param/postform')
        // const formData = new FormData(formEl)
        // xhr.send(formData)

        // 2.4. post: json
        xhr.open('post', 'http://xxx.32:1888/02_param/postjson')
        xhr.setRequestHeader('Content-type', 'application/json')
        xhr.send(JSON.stringify({name: "michael", age:18, height: 1.8}))

        // 4. send request
        // xhr.send()
    }
    clearData.onclick = () => {
        dataInput.value = ""
    }

  </script>

</body>
</html>

1.7. encapsulate an ajax function to send requests

<!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>JS-learn</title>
</head>
<body>
    <button class="send">send request</button>
  
  <script>

    // my ajax request class
    function myAjax({
      url,
      method = 'get',
      data = {},
      headers = {},
      success,  // callback function after sending requeset successfully
      failure   // callback function where there is any error 
    } = {}){
      // 1. create a XMLHttpRequeset
      const xhr = new XMLHttpRequest()

      //  2. monitor the data
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          success && success()
        } else {
          failure && failure({status: xhr.status, message: xhr.statusText})
        }
      }

      // 3. set the response type
      xhr.responseType = 'json'

      // 4. configure open
      if (method.toUpperCase() === 'GET') {
        const queryStr = []
        for (const key in data) {
          queryStr.push(`${key}=${data[key]}`)
        }

        url = url + '?' + queryStr.join('&')
        xhr.open(method, url)
        xhr.send()
      }else {
        xhr.open(method, url)
        xhr.setRequestHeader('Content-type', 'application/json')
        xhr.send(JSON.stringify(data))
      }

      return xhr

    }

    const sendBtn = document.querySelector(".send")
    
    // sendBtn.onclick = function getData(){
    //   myAjax({
    //     url: "http://xxx.32:1888/02_param/gest",
    //     method: "GET",
    //     data: {
    //       name: "michael",
    //       age: 18
    //     },
    //     success: function(res) {
    //       console.log("res:", res)
    //     },
    //     failure: function(err) {
    //       alert(err.message)
          
    //     }
    //   })
    // }
    sendBtn.onclick = function getData(){
      myAjax({
        url: "http://xxx.32:1888/02_param/postjson",
        method: "post",
        data: {
          name: "michael",
          age: 18
        },
        success: function(res) {
          console.log("res:", res)
        },
        failure: function(err) {
          alert(err.message)
          
        }
      })
    }
  </script>

</body>
</html>

1.8. encapsulate an ajax function to send requests with Promise

function myAjax({
    url,
    method = "get",
    data = {},
    timeout = 10000,
    headers = {}, // token 
} = {}) {
    // 1. create a XMLHttpRequest object
    const xhr = new XMLHttpRequest()

    // 2. create a promise object
    const promise = new Promise((resolve, reject) => {

        // 3. monitor data
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response)
            } else {
                reject({ status: xhr.status, message: xhr.statusText })
            }
        }

        // 4. set response type and timeout
        xhr.responseType = 'json'
        xhr.timeout = timeout

        // 5. configure open
        if (method.toUpperCase() === 'GET') {
            const queryStr = []
            for (const key in data) {
                queryStr.push(`${key}&${data[key]}`)
            }
            url = url + '?' + queryStr.join('&')
            xhr.open(method, url)
            xhr.send()
        } else {
            xhr.open(method, url)
            xhr.setRequestHeader('Content-type', 'application/json')
            xhr.send(JSON.stringify(data))
        }
    })

    promise.xhr = xhr

    return promise
}

2. Fetch

2.1. fetch demo

<!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>Fetch</title>
</head>
<body>
    <button class="send">send request</button>
    <script>

        const sendBtn = document.querySelector('.send')
        // 1. fetch send http request
        // sendBtn.onclick = () => {
        //     fetch('http://xxx.32:8000/home/multidata').then(result => {
        //         console.log(result)
        //     }).catch(reason => {
        //         console.log(reason)
        //     })
        // }

        // 2. optimize code when using fetch
        // 2.1. first solution
        // sendBtn.onclick =  () => {
        //     fetch('http://xxx.32:8000/home/multidata').then(result => {
        //         return result.json()
        //     }).then(result => {
        //         console.log('result: ', result)
        //     }).catch(reason => {
        //         console.log('error: ', reason)
        //     })
        // }

        // 2.2. second solution
        // async function getData(){
        //     const response = await fetch('http://xxx.32:8000/home/multidata')
        //     const result = await response.json()
        //     console.log('result: ', result)
        // }

        // sendBtn.onclick = getData

        // 3. send post request with params
        // 3.1. send json 
        // async function getData() {
        //     const response = await fetch('http://xxx.32:1888/02_param/postjson', {
        //         method: 'post',
        //         headers: { 'Content-type': 'application/json' },
        //         body: JSON.stringify({
        //             name: 'michael',
        //             age: 18
        //         })
        //     })

        //     console.log(response.ok, response.status, response.statusText)
        //     const result = await response.json()
        //     console.log('result: ', result)

        // }

        // sendBtn.onclick = getData

        // 3.2. send form
        async function getDate() {
            const formData = new FormData()
            formData.append('name', 'michael')
            formData.append('age', 18)
            const response = await fetch('http://xxxx.32:1888/02_param/postform', {
                method: 'post',
                body: formData
            })

            console.log(response.ok, response.status, response.statusText)

            const result = await response.json()
            console.log('result: ', result)
        }
        sendBtn.onclick = getDate

    </script>
</body>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/362187.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

mysql和sqlserver查询数据库表的数量的方法

一、mysql查询数据库表的数量 1、查询mysql下所有数据库表的数量 SELECT COUNT(*) TABLES, table_schema FROM information_schema.TABLES GROUP BY table_schema; 2、查询指定数据库的表的数量 SELECT COUNT(*) TABLES, table_schema FROM information_schema.TABLES WHER…

LeetCode第494题-目标和-python实现-图解思路与手撕代码

LeetCode第494题-目标和-python实现-图解思路与手撕代码 文章目录一、题目描述二、解题思路与代码实现1.解题思路2.代码实现总结一、题目描述 二、解题思路与代码实现 1.解题思路 这道题可以进行递归&#xff0c;遍历数组&#xff0c;对于当前这个数字&#xff0c;要么加上要…

Revit项目浏览器的标准设置应用和快速视图样板?

一、Revit项目浏览器的标准设置应用 设计院阶段的BIM应用&#xff0c;主要是Revit出施工图方面&#xff0c;需要涉及到很多标准的制定方面的问题&#xff0c;而且这个标准不仅仅是一个命名标准&#xff0c;还有很多的符合本院的出图标准等等&#xff0c;本期就不做详细讨论&…

【论文阅读】SCRFD: Sample and Computation 重分配的高效人脸检测

原始题目Sample and Computation Redistribution for Efficient Face Detection中文名称采样和计算 重分配的 高效人脸检测发表时间2021年5月10日平台ICLR-2022来源Imperial College&#xff0c; InsightFace文章链接https://arxiv.org/pdf/2105.04714.pdf开源代码官方实现&…

重压之下,特斯拉并不心甘情愿地召回FSD

/ 导读 /近日&#xff0c;美国国家公路交通安全管理局&#xff08;NHTSA&#xff09;宣布&#xff0c;其将召回近37万辆已安装或待安装全自动驾驶测试版&#xff08;FSD Beta&#xff09;的汽车。其实早在今年1月份的时候&#xff0c;NHTSA就要求特斯拉提交召回申请。而特斯拉在…

LabVIEW快速创建事件插件

LabVIEW快速创建事件插件此插件包含在LabVIEW2018及更高版本中。如果使用的是LabVIEW2017或更早版本&#xff0c;则只需从此处下载并安装它。在控件和控制终端上添加新的“创建>事件结构”&#xff1a;选择此选项将在控件上为指定事件配置新的事件结构&#xff1a;一些附加说…

jupyter使用指北:如何打开.ipynb文件|修改jupyter notebook的默认路径|在jupyter按照包

文章目录打开.ipynb文件、修改jupyter的默认路径笨办法好办法用jupyter notebook直接安装包运行代码打开.ipynb文件、修改jupyter的默认路径 比如&#xff0c;在该目录下有一个.ipynb文件&#xff0c;想用jupyter notebook直接打开&#xff1a; 笨办法 先进入jupyter再把文…

FFMPEG自学二 ⾳频编码实战

一、FFmpeg编码流程二、流程关键函数avcodec_find_encoder&#xff1a;根据指定的AVCodecID查找注册的编码器。 avcodec_alloc_context3&#xff1a;为AVCodecContext分配内存。 avcodec_open2&#xff1a;打开编码器。 avcodec_send_frame&#xff1a;将AVFrame⾮压缩数据给…

LVGL Styles

LVGL StylesGet started按钮添加标签按钮添加风格滑动条值显示StylesSize stylesBackground stylesBorder stylesOutline stylesShadow stylesImage stylesArc stylesText stylesLine stylesGet started 按钮添加标签 /*** brief 按钮事件回调函数* param e */ void btn_eve…

【Python实战】一大波高颜值主播来袭:快看,某网站颜值排名,为了这个排名我可是大费周章啦,第一名不亏是你...(人脸检测+爬虫实战)

导语 民间一直有个传闻......「听说某站的小哥哥小姐姐颜值都很高哦&#xff01;」 &#xff08;不是颜值高才能加入&#xff0c;是优秀的人恰好颜值高&#xff09; 所有文章完整的素材源码都在&#x1f447;&#x1f447; 粉丝白嫖源码福利&#xff0c;请移步至CSDN社区或文末…

Qt C++ 自定义仪表盘控件03

简介仪表盘是工控领域不可缺少的一类软件UI元素&#xff0c;通常出现在各类电子看板软件上&#xff0c;以及一些高级的上位机软件界面上&#xff0c;目的是将繁杂的数据转化为可视化的图表能大幅提高后台管理效率。本文分享了几个经典常用的仪表盘控件&#xff0c;在项目中可以…

系列一、SQL

一、SQL分类 二、DDL 定义&#xff1a;Data Definition Language&#xff0c;数据定义语言&#xff0c;用来定义数据库对象(数据库&#xff0c;表&#xff0c;字段) 2.1、数据库操作 2.1.1、查询所有数据库 show databases; 2.1.2、查询当前数据库 select database(); 2.…

Pytorch平均池化nn.AvgPool2d()使用记录

【pytorch官方文档】&#xff1a;https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html?highlightavgpool2d#torch.nn.AvgPool2dtorch.nn.AvgPool2d()作用在由多通道组成的输入特征中进行2D平均池化计算函数torch.nn.AvgPool2d(kernel_size, strideNone, paddi…

在 ubuntu 中切换使用不同版本的 python

引言有时我们不得不在同一台 ubuntu 中使用不同版本的 python 环境。本文的介绍就是可以在 ubuntu 上同时安装几个不同版本的 python&#xff0c;然后你可以随时指定当前要使用的 python 版本。步骤检查当前的 python 版本$ python3 --version python 3.6.8我的版本是 3.6.8假设…

Renegade:基于MPC+Bulletproofs构建的anonymous DEX

1. 引言 白皮书见&#xff1a; Renegade Whitepaper: Protocol Specification, v0.6 开源代码见&#xff1a; https://github.com/renegade-fi/renegade&#xff08;Renegade p2p网络每个节点的核心网络和密码逻辑&#xff09;https://github.com/renegade-fi/mpc-bulletpr…

OSPF(开放式最短路径优先协议)、ACL(访问控制列表)、NAT

一、OSPF -- &#xff08;开放式最短路径优先协议&#xff09; 基于组播更新 --- 224.0.0.5 224.0.0.6 1、协议类型&#xff1a;无类别链路状态的IGP协议 无类别&#xff1a;带精确掩码链路状态&#xff1a;不共享路由&#xff0c;共享拓扑&#xff08;共享LSA&#xff09;…

Windows平台Python编程必会模块之pywin32

在Windows平台上&#xff0c;从原来使用C/C编写原生EXE程序&#xff0c;到使用Python编写一些常用脚本程序&#xff0c;成熟的模块的使用使得编程效率大大提高了。 不过&#xff0c;python模块虽多&#xff0c;也不可能满足开发者的所有需求。而且&#xff0c;模块为了便于使用…

产品未出 百度朋友圈“开演”

ChatGPT这股AI龙卷风刮到国内时&#xff0c;人们齐刷刷望向百度&#xff0c;这家在国内对AI投入最高的公司最终出手了&#xff0c;大模型新项目文心一言&#xff08;ERNIE Bot&#xff09;将在3月正式亮相&#xff0c;对标微软投资的ChatGPT。 文心一言产品未出&#xff0c;百…

[python入门㊿] - python如何打断点

目录 ❤ 什么是bug(缺陷) ❤ python代码的调试方式 ❤ 使用 pdb 进行调试 测试代码示例 利用 pdb 调试 退出 debug debug 过程中打印变量 停止 debug 继续执行程序 debug 过程中显示代码 使用函数的例子 对函数进行 debug 在调试的时候动态改变值 ❤ 使用 PyC…

el-cascader v-model 绑定值改变了,但是界面没变化

查了很多资料&#xff0c;解决办法各异&#xff0c;但以下两个没有用 &#xff08;1&#xff09;this.$forceUpdate()强制更新渲染&#xff0c;没用。 &#xff08;2&#xff09;使用v-if和this.ifPanel false去控制el-cascader的显示&#xff0c;目的也是重新渲染&#xff…