当前位置: 首页 > 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>
http://www.lryc.cn/news/15415.html

相关文章:

  • mathtype7.0最新版安装下载及使用教程
  • 响应状态码
  • 第六章.卷积神经网络(CNN)—CNN的实现(搭建手写数字识别的CNN)
  • 【go】defer底层原理
  • TypeScript 学习笔记
  • 【C++】map和set的使用
  • 微电影广告具有哪些特点?
  • Android RxJava框架源码解析(四)
  • Linux信号-进程退出状态码
  • springcloud+vue实现图书管理系统
  • GEE学习笔记 六十:GEE中生成GIF动画
  • react中的useEffect
  • 故障安全(Crash-Safe) 复制
  • Spring aop之针对注解
  • 【JavaScript速成之路】JavaScript数据类型转换
  • 21-绑定自定义事件
  • 【Mysql】触发器
  • CODESYS开发教程11-库管理器
  • 【UnityAR相关】Unity Vuforia扫图片成模型具体步骤
  • 2023年全国最新保安员精选真题及答案2
  • keil5安装了pack包但是还是不能选择device
  • 秒杀系统设计
  • 全面认识数据指标体系
  • 热榜首推!阿里内部都在用的Java后端面试笔记,主流技术全在里面了!备战2023Java面试,拿理想offer
  • Android架构设计——【 APT技术实现butterknife框架 】
  • 线程的基本概念
  • java面试题中常见名词注解
  • SpringAOP从入门到源码分析大全,学好AOP这一篇就够了(二)
  • 华为OD机试 - 斗地主(C++) | 附带编码思路 【2023】
  • 【存储】etcd的存储是如何实现的(3)-blotdb