当前位置:网站首页>Axios learning notes (2): easy to understand the use of XHR and how to package simple Axios
Axios learning notes (2): easy to understand the use of XHR and how to package simple Axios
2020-11-06 20:42:00 【Tell me Zhan to hide】
Use
XMLHttpRequest(XHR) Objects can interact with the server . You can learn from URL get data , And without having to refresh the entire page . This allows the web page to update the local content of the page without affecting the user's operation . stay AJAX Programming ,XMLHttpRequestHeavily used .

List of articles
1. understand XHR
- Use XMLHttpRequest(XHR) Objects can interact with the server , That is, sending ajax request
- The front end can get data , And without having to refresh the entire page
- This makes Web Pages can only update parts of the page , And not affect the user's operation
The difference is general http Ask for something to do with ajax request
- ajax Requests are special http request
- For the server side , It doesn't make any difference , The difference is on the browser side
- The browser sends a request : Only XHR or fetch That's what's coming out ajax request , All other requests are true and wrong ajax request
- The browser side receives a response
- (1) General request : Browsers generally display the response data directly , That is, refresh, as we often call it / Jump to the page
(2) ajax request : The browser does not update the interface , Just call the monitored callback Function and pass in response correlation number
3. API
-
XMLHttpRequest(): establish XHR Object's constructor
-
status: Response status code value , such as 200,404
-
statusText: Response status text
-
readyState: Read only property that identifies the status of the request
0: initial <br /> 1: open() after <br /> 2: send() after <br /> 3: In request <br /> 4: Request completed -
onreadystatechange: binding readyState Change monitoring
-
responseType: Specify the corresponding data , If it is ’json’, After the response is obtained, the response body data will be automatically parsed
-
response: Response body data , The type depends on responseType The specified
-
timeout: Specify the request timeout , The default is 0 There is no limit
-
ontimeout: Binding timeout monitoring
-
onerror: Binding requests network error monitoring
-
open(): Initialize a request , Parameter is : (method, url[, async])
-
send(data): Send a request
-
abort(): Interrupt request
-
getResponseHeader(name): Gets the response header value for the specified name
-
getAllResponseHeaders(): Gets the string of all response headers
16. setRequestHeader(name, value): Set request header
4. XHR Of ajax encapsulation , It's also a simple version of axios
4.1 characteristic
- The return value of the function promise, The result of success is response, The abnormal result is error
- Can handle multiple types of requests :GET/POST/PUT/DELETE
- The parameter of the function is a configuration object
{
url: '', // Request address
method: '', // Request mode GET/POST/PUT/DELETE
params: {
}, // GET/DELETE Requested query Parameters
data: {
}, // POST or DELETE Requested body parameter
}
- Respond to json Data is automatically parsed to js The object of / Array
4.2 A simple version of axios Source code
function axios({
url,
method='GET',
params={
},
data={
}
}) {
// Return to one promise object
return new Promise((resolve, reject) => {
// Handle method( Turn capitalization )
method = method.toUpperCase()
// Handle query Parameters ( Joining together to url On ) id=1&xxx=abc
/* { id: 1, xxx: 'abc' } */
let queryString = ''
Object.keys(params).forEach(key => {
queryString += `${ key}=${ params[key]}&`
})
if (queryString) {
// id=1&xxx=abc&
// Remove the last &
queryString = queryString.substring(0, queryString.length-1)
// Receive url
url += '?' + queryString
}
// 1. Asynchronous execution ajax request
// establish xhr object
const request = new XMLHttpRequest()
// Open the connection ( Initialization request , No request )
request.open(method, url, true)
// Send a request
if (method==='GET' || method==='DELETE') {
request.send()
} else if (method==='POST' || method==='PUT'){
request.setRequestHeader('Content-Type', 'application/json;charset=utf-8') // Tell the server that the format of the requester is json
request.send(JSON.stringify(data)) // send out json Format requester parameters
}
// Monitoring of binding state changes
request.onreadystatechange = function () {
// If the request is not completed , End directly
if (request.readyState!==4) {
return
}
// If the response status code is [200, 300) Between represents success , Otherwise failure
const {
status, statusText} = request
// 2.1. If the request succeeds , call resolve()
if (status>=200 && status<=299) {
// Prepare the result data object response
const response = {
data: JSON.parse(request.response),
status,
statusText
}
resolve(response)
} else {
// 2.2. If the request fails , call reject()
reject(new Error('request error status is ' + status))
}
}
})
}
版权声明
本文为[Tell me Zhan to hide]所创,转载请带上原文链接,感谢
边栏推荐
- Outsourcing is really difficult. As an outsourcer, I can't help sighing.
- Live broadcast preview | micro service architecture Learning Series live broadcast phase 3
- How does filecoin's economic model and future value support the price of fil currency breaking through thousands
- 文件过多时ls命令为什么会卡住?
- Elasticsearch Part 6: aggregate statistical query
- Get twice the result with half the effort: automation without cabinet
- 只有1个字节的文件实际占用多少磁盘空间
- 一路踩坑,被迫聊聊 C# 代码调试技巧和远程调试
- nacos、ribbon和feign的簡明教程
- image operating system windows cannot be used on this platform
猜你喜欢

EOS founder BM: what's the difference between UE, UBI and URI?

What is alicloud's experience of sweeping goods for 100 yuan?

一路踩坑,被迫聊聊 C# 代码调试技巧和远程调试

代码生成器插件与Creator预制体文件解析

事件监听问题

Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom

2020年第四届中国 BIM (数字建造)经理高峰论坛即将在杭举办
![[Xinge education] poor learning host computer series -- building step 7 Simulation Environment](/img/f8/4bb6f887d56a7a18eb55cbec579204.jpg)
[Xinge education] poor learning host computer series -- building step 7 Simulation Environment

Outsourcing is really difficult. As an outsourcer, I can't help sighing.

意派Epub360丨你想要的H5模板都在这里,电子书、大转盘、红包雨、问卷调查……
随机推荐
Swagger 3.0 brushes the screen every day. Does it really smell good?
How to demote domain controllers and later in Windows Server 2012
Humor: hacker programming is actually similar to machine learning!
What are Devops
Shh! Is this really good for asynchronous events?
electron 實現檔案下載管理器
Flink's datasource Trilogy 2: built in connector
Read the advantages of Wi Fi 6 over Wi Fi 5 in 3 minutes
大道至简 html + js 实现最朴实的小游戏俄罗斯方块
Analysis of ThreadLocal principle
【转发】查看lua中userdata的方法
Azure data factory (3) integrate azure Devops to realize CI / CD
嘉宾专访|2020 PostgreSQL亚洲大会阿里云数据库专场:曾文旌
Bitcoin once exceeded 14000 US dollars and is about to face the test of the US election
解决 WPF 绑定集合后数据变动界面却不更新的问题
游戏开发中的新手引导与事件管理系统
行为型模式之解释器模式
[efficiency optimization] Nani? Memory overflow again?! It's time to sum up the wave!!
如何在终端启动Coda 2中隐藏的首选项?
使用 Iceberg on Kubernetes 打造新一代雲原生資料湖