当前位置: 首页 > news >正文

JavaScript-XHR-深入理解

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")// debuggerbuttonData.onclick = function getData(){// 1. create XMLHttpRequest objectconst xhr = new XMLHttpRequest()// 2. monitor the change of status (macrotask)xhr.onreadystatechange = () => {if (xhr.readyState !== XMLHttpRequest.DONE) return// get the response dataconst resJSON = JSON.parse(xhr.response)console.log('response: ', resJSON)// data = resJSONdataInput.value = JSON.stringify(resJSON)}// 2. configure request openxhr.open('get', 'http://123.xxx:8000/home/multidata')// 4. send requestxhr.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")// debuggerbuttonData.onclick = function getData(){// 1. create XMLHttpRequest objectconst 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 dataconst resJSON = JSON.parse(xhr.response)console.log('response: ', resJSON)console.log('status: ', xhr.status)console.log('xhr: ', xhr)// data = resJSONdataInput.value = JSON.stringify(resJSON)}// 2. configure request openxhr.open('get', 'http://xxxx.32:8000/home/multidata', true)// 4. send requestxhr.send()console.log('here is the log after sending')}clearData.onclick = () => {dataInput.value = ""}</script></body>
</html>

在这里插入图片描述

        // 2. configure request openxhr.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")// debuggerbuttonData.onclick = function getData(){// 1. create XMLHttpRequest objectconst xhr = new XMLHttpRequest()// 2. monitor onload eventxhr.onload = () => {console.log('onload')dataInput.value = xhr.response}// 2. configure request openxhr.open('get', 'http://xxx.32:8000/home/multidata', false)// 4. send requestxhr.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")// debuggerbuttonData.onclick = function getData(){// 1. create XMLHttpRequest objectconst xhr = new XMLHttpRequest()// 2. monitor onload eventxhr.onload = () => {console.log(xhr.status, xhr.statusText)// make a judgement based on http status codeif (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 openxhr.open('get', 'http://xxx.32:8000/home/mudltidata', false)// 4. send requestxhr.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")// debuggersendBtn.onclick = function getData(){// 1. create XMLHttpRequest objectconst xhr = new XMLHttpRequest()// 2. monitor onload eventxhr.onload = () => {console.log(xhr.status, xhr.statusText)// make a judgement based on http status codeif (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: jsonxhr.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 classfunction myAjax({url,method = 'get',data = {},headers = {},success,  // callback function after sending requeset successfullyfailure   // callback function where there is any error } = {}){// 1. create a XMLHttpRequesetconst xhr = new XMLHttpRequest()//  2. monitor the dataxhr.onload = function() {if (xhr.status >= 200 && xhr.status < 300) {success && success()} else {failure && failure({status: xhr.status, message: xhr.statusText})}}// 3. set the response typexhr.responseType = 'json'// 4. configure openif (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 objectconst xhr = new XMLHttpRequest()// 2. create a promise objectconst promise = new Promise((resolve, reject) => {// 3. monitor dataxhr.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 timeoutxhr.responseType = 'json'xhr.timeout = timeout// 5. configure openif (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 = xhrreturn 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 formasync 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>

相关文章:

JavaScript-XHR-深入理解

JavaScript-XHR-深入理解1. XHR(Asynchronous JavaScript And XML)初始1.1. xhr request demo1.2. status of XHRHttpRequest1.3. send synchronous request by xhr1.4. onload监听数据加载完成1.5. http status code1.6. get/post request with josn/form/urlcoded1.7. encaps…...

mathtype7.0最新版安装下载及使用教程

MathType是一款专业的数学公式编辑器&#xff0c;理科生专用的必备工具&#xff0c;可应用于教育教学、科研机构、工程学、论文写作、期刊排版、编辑理科试卷等领域。2014年11月&#xff0c;Design Science将MathType升级到MathType 6.9版本。在苏州苏杰思网络有限公司与Design…...

响应状态码

✨作者&#xff1a;猫十二懿 ❤️‍&#x1f525;账号&#xff1a;CSDN 、掘金 、个人博客 、Github &#x1f389;公众号&#xff1a;猫十二懿 一、状态码大类 状态码分类说明1xx响应中——临时状态码&#xff0c;表示请求已经接受&#xff0c;告诉客户端应该继续请求或者如果…...

第六章.卷积神经网络(CNN)—CNN的实现(搭建手写数字识别的CNN)

第六章.卷积神经网络(CNN) 6.2 CNN的实现(搭建手写数字识别的CNN) 1.网络构成 2.代码实现 import pickle import matplotlib.pyplot as plt import numpy as np import sys, ossys.path.append(os.pardir)from dataset.mnist import load_mnist from collections import Order…...

【go】defer底层原理

defer的作用 defer声明的函数在当前函数return之后执行&#xff0c;通常用来做资源、连接的关闭和缓存的清除等。 A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly u…...

TypeScript 学习笔记

最近在学 ts 顺便记录一下自己的学习进度&#xff0c;以及一些知识点的记录&#xff0c;可能不会太详细&#xff0c;主要是用来巩固和复习的&#xff0c;会持续更新 前言 想法 首先我自己想说一下自己在学ts之前&#xff0c;对ts的一个想法和印象&#xff0c;在我学习之前&a…...

【C++】map和set的使用

map和set一、set1.1 set的介绍1.2 set的使用1.2.1 set的构造1.2.2 set的迭代器1.2.3 set的修改1.2.3.1 insert && find && erase1.2.3.2 count1.3 multiset二、map2.1 map的介绍2.2 map的使用2.2.1 map的修改2.2.1.1 insert2.2.1.2 统计次数2.3 multimap一、se…...

微电影广告具有哪些特点?

微电影广告是广告主投资的&#xff0c;以微电影为形式载体&#xff0c;以新媒体为主要传播载体&#xff0c;综合运用影视创作手法拍摄的集故事性、艺术性和商业性于一体的广告。它凭借精彩的电影语言和强大的明星效应多渠道联动传播&#xff0c;润物细无声地渗透和传递着商品信…...

Android RxJava框架源码解析(四)

目录一、观察者Observer创建过程二、被观察者Observable创建过程三、subscribe订阅过程四、map操作符五、线程切换原理简单示例1&#xff1a; private Disposable mDisposable; Observable.create(new ObservableOnSubscribe<String>() {Overridepublic void subscribe(…...

Linux信号-进程退出状态码

当进程因收到信号被终止执行退出后&#xff0c;父进程可以通过wait或waitpid得到它的exit code。进程被各信号终止的退出状态码总结如下&#xff1a;信号编号信号名称信号描述默认处理方式Exit code1SIGHUP挂起终止12SIGINT终端中断终止23SIGQUIT终端退出终止、coredump1314SIG…...

springcloud+vue实现图书管理系统

一、前言&#xff1a; 今天我们来分享一下一个简单的图书管理系统 我们知道图书馆系统可以有两个系统&#xff0c;一个是管理员管理图书的系统&#xff0c;管理员可以&#xff08;1&#xff09;查找某一本图书情况、&#xff08;2&#xff09;增加新的图书、&#xff08;3&…...

GEE学习笔记 六十:GEE中生成GIF动画

生成GIF动画这个是GEE新增加的功能之一&#xff0c;这一篇文章我会简单介绍一下如何使用GEE来制作GIF动画。 相关API如下&#xff1a; 参数含义&#xff1a; params&#xff1a;设置GIF动画显示参数&#xff0c;详细的参数可以参考ee.data.getMapId() callback&#xff1a;回调…...

react中的useEffect

是函数组件中执行的副作用&#xff0c;副作用就是指每次组件更新都会执行的函数&#xff0c;可以用来取代生命周期。 1. 基本用法 import { useEffect } from "react"; useEffect(()>{console.log(副作用); });2. 副作用分为需要清除的和不需要清除 假如设置…...

故障安全(Crash-Safe) 复制

二进制日志记录是故障安全的:MySQL 仅记录完成的事件或事务使用 sync-binlog 提高安全性默认值是1&#xff0c;最安全的&#xff0c;操作系统在每次事务后写入文件将svnc-binloq 设置为0&#xff0c;当操作系统根据其内部规则写入文件的同时服务器崩溃时性能最好但事务丢失的可…...

Spring aop之针对注解

前言 接触过Spring的都知道&#xff0c;aop是其中重要的特性之一。笔者在开发做项目中&#xff0c;aop更多地是要和注解搭配&#xff1a;在某些方法上加上自定义注解&#xff0c;然后要对这些方法进行增强(很少用execution指定&#xff0c;哪些包下的哪些方法要增强)。那这时就…...

【JavaScript速成之路】JavaScript数据类型转换

&#x1f4c3;个人主页&#xff1a;「小杨」的csdn博客 &#x1f525;系列专栏&#xff1a;【JavaScript速成之路】 &#x1f433;希望大家多多支持&#x1f970;一起进步呀&#xff01; 文章目录前言数据类型转换1&#xff0c;转换为字符串型1.1&#xff0c;利用“”拼接转换成…...

21-绑定自定义事件

绑定自定义事件 利用自定义事件获取子组件的值 父组件给子组件绑定一个自定义事件&#xff0c;实际上是绑定到了子组件的实例对象vc上&#xff1a; <!-- 自定义myEvent事件 --> <Student v-on:myEventgetStudentName/>在父组件中编写getStudentName的实现&#…...

【Mysql】触发器

【Mysql】触发器 文章目录【Mysql】触发器1. 触发器1.1 介绍1.2 语法1.2.1 创建触发器1.2.2 查看触发器1.2.3 删除触发器1.2.4 案例1. 触发器 1.1 介绍 触发器是与表有关的数据库对象&#xff0c;指在insert、update、delete之前(BEFORE)或之后(AFTER)&#xff0c;触发并执行…...

CODESYS开发教程11-库管理器

今天继续我们的小白教程&#xff0c;老鸟就不要在这浪费时间了&#x1f60a;。 前面一期我们介绍了CODESYS的文件读写函数库SysFile。大家可能发现了&#xff0c;在CODESYS的开发中实际上是离不开各种库的使用&#xff0c;其中包括系统库、第三方库以及用户自己开发的库。实际…...

【UnityAR相关】Unity Vuforia扫图片成模型具体步骤

1 资产准备 导入要生成的fbx模型&#xff08;带有材质&#xff09;&#xff0c; 你会发现导入fbx的材质丢失了&#xff1a; 选择Standard再Extract Materials导出材质到指定文件夹下&#xff08;我放在Assets->Materials了 ok啦&#xff01; 材质出现了&#xff0c; 模型…...

day52 ResNet18 CBAM

在深度学习的旅程中&#xff0c;我们不断探索如何提升模型的性能。今天&#xff0c;我将分享我在 ResNet18 模型中插入 CBAM&#xff08;Convolutional Block Attention Module&#xff09;模块&#xff0c;并采用分阶段微调策略的实践过程。通过这个过程&#xff0c;我不仅提升…...

3.3.1_1 检错编码(奇偶校验码)

从这节课开始&#xff0c;我们会探讨数据链路层的差错控制功能&#xff0c;差错控制功能的主要目标是要发现并且解决一个帧内部的位错误&#xff0c;我们需要使用特殊的编码技术去发现帧内部的位错误&#xff0c;当我们发现位错误之后&#xff0c;通常来说有两种解决方案。第一…...

关于uniapp展示PDF的解决方案

在 UniApp 的 H5 环境中使用 pdf-vue3 组件可以实现完整的 PDF 预览功能。以下是详细实现步骤和注意事项&#xff1a; 一、安装依赖 安装 pdf-vue3 和 PDF.js 核心库&#xff1a; npm install pdf-vue3 pdfjs-dist二、基本使用示例 <template><view class"con…...

【从零开始学习JVM | 第四篇】类加载器和双亲委派机制(高频面试题)

前言&#xff1a; 双亲委派机制对于面试这块来说非常重要&#xff0c;在实际开发中也是经常遇见需要打破双亲委派的需求&#xff0c;今天我们一起来探索一下什么是双亲委派机制&#xff0c;在此之前我们先介绍一下类的加载器。 目录 ​编辑 前言&#xff1a; 类加载器 1. …...

日常一水C

多态 言简意赅&#xff1a;就是一个对象面对同一事件时做出的不同反应 而之前的继承中说过&#xff0c;当子类和父类的函数名相同时&#xff0c;会隐藏父类的同名函数转而调用子类的同名函数&#xff0c;如果要调用父类的同名函数&#xff0c;那么就需要对父类进行引用&#…...

零知开源——STM32F103RBT6驱动 ICM20948 九轴传感器及 vofa + 上位机可视化教程

STM32F1 本教程使用零知标准板&#xff08;STM32F103RBT6&#xff09;通过I2C驱动ICM20948九轴传感器&#xff0c;实现姿态解算&#xff0c;并通过串口将数据实时发送至VOFA上位机进行3D可视化。代码基于开源库修改优化&#xff0c;适合嵌入式及物联网开发者。在基础驱动上新增…...

WPF八大法则:告别模态窗口卡顿

⚙️ 核心问题&#xff1a;阻塞式模态窗口的缺陷 原始代码中ShowDialog()会阻塞UI线程&#xff0c;导致后续逻辑无法执行&#xff1a; var result modalWindow.ShowDialog(); // 线程阻塞 ProcessResult(result); // 必须等待窗口关闭根本问题&#xff1a…...

华为OD最新机试真题-数组组成的最小数字-OD统一考试(B卷)

题目描述 给定一个整型数组,请从该数组中选择3个元素 组成最小数字并输出 (如果数组长度小于3,则选择数组中所有元素来组成最小数字)。 输入描述 行用半角逗号分割的字符串记录的整型数组,0<数组长度<= 100,0<整数的取值范围<= 10000。 输出描述 由3个元素组成…...

人工智能 - 在Dify、Coze、n8n、FastGPT和RAGFlow之间做出技术选型

在Dify、Coze、n8n、FastGPT和RAGFlow之间做出技术选型。这些平台各有侧重&#xff0c;适用场景差异显著。下面我将从核心功能定位、典型应用场景、真实体验痛点、选型决策关键点进行拆解&#xff0c;并提供具体场景下的推荐方案。 一、核心功能定位速览 平台核心定位技术栈亮…...

Matlab实现任意伪彩色图像可视化显示

Matlab实现任意伪彩色图像可视化显示 1、灰度原始图像2、RGB彩色原始图像 在科研研究中&#xff0c;如何展示好看的实验结果图像非常重要&#xff01;&#xff01;&#xff01; 1、灰度原始图像 灰度图像每个像素点只有一个数值&#xff0c;代表该点的​​亮度&#xff08;或…...