当前位置:网站首页>Brief introduction to XHR - basic use of XHR
Brief introduction to XHR - basic use of XHR
2022-07-06 13:49:00 【Ling Xiaoding】
List of articles
XMLHttpRequest API summary
attribute :
readyState
xhr The status code 4 The response body is receivedstatus
Get status coderesponseText
Get the response body , Text formatresponseXML
Get the response body ,xml Formatonreadtstatechange
event , Whenxhr.readyState
Triggered by property changeonload
event , Response received
Method :
open(method, url, async)
Set the mode of request , The path of the request , Sync / asynchronoussend(requestBody)
Send request bodysetRequestHeader(key, value)
Set request headergetResponseHeader(key)
Get response header
How to request
onload
: Easy to get the response events
GET
- establish
xhr
object- call
open
Method , Set the request mode andURL
- call
send
Method , send out- When the request response process is over ( Called
xhr.onload
event ), adoptresponseText
Property to receive the data returned by the serverajax
Ofget
request
document.getElementById('btn').onclick = function () {
// establish xhr object
let xhr = new XMLHttpRequest()
// call open Method , Set the request mode and URL
xhr.open('GET', 'http://127.0.0.1:3000/search')
// call send Method , send out
xhr.send()
// When the request response process is over ( Called xhr.onload event ), adopt responseText Property to receive the data returned by the server
xhr.onload = function () {
console.log(xhr.responseText)
}
}
Be careful :GET
request IE
Caching and solutions
- reason : Two requests
url
Exactly the same , On the second request ,IE
No more requests will be sent to the server , Instead, use the result returned for the first time - solve : Make every request
url
atypism , You can add timestamp parameters
POST
- establish
xhr
object- call
open
Method , Set the request mode andURL
- call
setRequestHeader( )
Method , Set upheader
head , Appointcontent-type
- call
send
Method , send out- When the request response is complete , Receive the data returned by the server
// establish xhr object
let xhr=new XMLHttpRequest()
// call open Method , Set the request mode and URL
xhr.open('POST', 'http://127.0.0.1:3000/search')
// call setRequestHeader( ) Method , Set up header head , Appoint content-type
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// call send Method , send out
xhr.send('x=11111')
// When the request response is complete , Receive the data returned by the server
xhr.onreadystatechange=function(){
if (xhr.readyState===4 || xhr.status===200) {
console.log(xhr.responseText);
}
}
Basics get The way and post Differences in methods
ajax
OfGET
Request andajax
Ofpost
request , The position of passing parameters is differentGET
The request can only carry a small number of parameters ,POST
There is no limit to the data carried by the request- Only
POST
Only by way of request can the file be uploaded
onreadystatechange and readyState
readyState
xhr
Of 5 States
readyState
The value of is 4, It indicates that the browser has completely received the data returned by the server
readyState | State description | explain |
---|---|---|
0 | UNSENT | agent (XHR) Be created , But not yet called open() Method |
1 | OPENED | open() Method has been called , It establishes the connection . |
2 | HEADERS_RECEIVED | send() Method has been called , And you can get the status line and the response header . |
3 | LOADING | Response body downloading ,responseText Property may already contain some data . |
4 | DONE | Response body download completed , You can use it directly responseText . |
onreadystatechange
- ajax The execution state changes ( When
readyState
When the value of is changed ) Will trigger - When the received data changes , This event will also be triggered
- He can replace
onload
event
Synchronous and asynchronous
xhr.open( )
The third parameter passes in a Boolean value- The function is to set whether the request is executed asynchronously , The default is
true
asynchronous ,false
For synchronization - Synchronization request
ajax
Synchronous request , Will be insend
The method is stuck there , When did the server return data , Subsequent code can be executed , Disfavor use- Asynchronous requests
ajax
Asynchronous request for , It will not block subsequent code execution , In favor of using
compatible
- IE5、IE6: No,
XMLHttpRequest
object
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
summary
Ajax
It's a set provided by the browser API
, Can pass JavaScript
call , So that we can control the request and response by code , Network programming .
This is the end of this article , If you feel it is still practical , It's OK to follow or like , Thank you very much! !
边栏推荐
- 7. Relationship between array, pointer and array
- Inaki Ading
- hashCode()与equals()之间的关系
- A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews
- 7-9 制作门牌号3.0(PTA程序设计)
- C language to achieve mine sweeping game (full version)
- 【九阳神功】2020复旦大学应用统计真题+解析
- 【VMware异常问题】问题分析&解决办法
- 【九阳神功】2019复旦大学应用统计真题+解析
- 仿牛客技术博客项目常见问题及解答(二)
猜你喜欢
【VMware异常问题】问题分析&解决办法
3. Input and output functions (printf, scanf, getchar and putchar)
1. First knowledge of C language (1)
扑克牌游戏程序——人机对抗
Programme de jeu de cartes - confrontation homme - machine
.Xmind文件如何上传金山文档共享在线编辑?
Wei Pai: the product is applauded, but why is the sales volume still frustrated
3. C language uses algebraic cofactor to calculate determinant
QT meta object qmetaobject indexofslot and other functions to obtain class methods attention
MySQL锁总结(全面简洁 + 图文详解)
随机推荐
Service ability of Hongmeng harmonyos learning notes to realize cross end communication
Pit avoidance Guide: Thirteen characteristics of garbage NFT project
[the Nine Yang Manual] 2019 Fudan University Applied Statistics real problem + analysis
6. Function recursion
canvas基础2 - arc - 画弧线
4. Binary search
ArrayList的自动扩容机制实现原理
C language to achieve mine sweeping game (full version)
[during the interview] - how can I explain the mechanism of TCP to achieve reliable transmission
【九阳神功】2022复旦大学应用统计真题+解析
1. C language matrix addition and subtraction method
Mode 1 two-way serial communication is adopted between machine a and machine B, and the specific requirements are as follows: (1) the K1 key of machine a can control the ledi of machine B to turn on a
5月14日杂谈
2022泰迪杯数据挖掘挑战赛C题思路及赛后总结
实验七 常用类的使用(修正帖)
Change vs theme and set background picture
4. Branch statements and loop statements
[面試時]——我如何講清楚TCP實現可靠傳輸的機制
实验九 输入输出流(节选)
7-14 错误票据(PTA程序设计)