当前位置:网站首页>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 :
readyStatexhr The status code 4 The response body is receivedstatusGet status coderesponseTextGet the response body , Text formatresponseXMLGet the response body ,xml Formatonreadtstatechangeevent , Whenxhr.readyStateTriggered by property changeonloadevent , 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
xhrobject- call
openMethod , Set the request mode andURL- call
sendMethod , send out- When the request response process is over ( Called
xhr.onloadevent ), adoptresponseTextProperty to receive the data returned by the serverajaxOfgetrequest
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
urlExactly the same , On the second request ,IENo more requests will be sent to the server , Instead, use the result returned for the first time - solve : Make every request
urlatypism , You can add timestamp parameters
POST
- establish
xhrobject- call
openMethod , Set the request mode andURL- call
setRequestHeader( )Method , Set upheaderhead , Appointcontent-type- call
sendMethod , 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
ajaxOfGETRequest andajaxOfpostrequest , The position of passing parameters is differentGETThe request can only carry a small number of parameters ,POSTThere is no limit to the data carried by the request- Only
POSTOnly by way of request can the file be uploaded
onreadystatechange and readyState
readyState
xhr Of 5 States
readyStateThe 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
readyStateWhen the value of is changed ) Will trigger - When the received data changes , This event will also be triggered
- He can replace
onloadevent
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
trueasynchronous ,falseFor synchronization - Synchronization request
ajaxSynchronous request , Will be insendThe method is stuck there , When did the server return data , Subsequent code can be executed , Disfavor use- Asynchronous requests
ajaxAsynchronous request for , It will not block subsequent code execution , In favor of using
compatible
- IE5、IE6: No,
XMLHttpRequestobject
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-11 机工士姆斯塔迪奥(PTA程序设计)
- FAQs and answers to the imitation Niuke technology blog project (III)
- C language Getting Started Guide
- [modern Chinese history] Chapter 9 test
- Thoroughly understand LRU algorithm - explain 146 questions in detail and eliminate LRU cache in redis
- 3. Input and output functions (printf, scanf, getchar and putchar)
- 为什么要使用Redis
- . Net6: develop modern 3D industrial software based on WPF (2)
- [hand tearing code] single case mode and producer / consumer mode
- 7. Relationship between array, pointer and array
猜你喜欢
随机推荐
【VMware异常问题】问题分析&解决办法
Cookie和Session的区别
Pit avoidance Guide: Thirteen characteristics of garbage NFT project
【九阳神功】2022复旦大学应用统计真题+解析
Miscellaneous talk on May 14
7-4 散列表查找(PTA程序设计)
5. Download and use of MSDN
Using qcommonstyle to draw custom form parts
7-5 走楼梯升级版(PTA程序设计)
A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews
7-3 构造散列表(PTA程序设计)
MySQL lock summary (comprehensive and concise + graphic explanation)
7-15 h0161. 求最大公约数和最小公倍数(PTA程序设计)
ArrayList的自动扩容机制实现原理
C language Getting Started Guide
7-9 制作门牌号3.0(PTA程序设计)
编写程序,模拟现实生活中的交通信号灯。
[the Nine Yang Manual] 2021 Fudan University Applied Statistics real problem + analysis
实验四 数组
canvas基础2 - arc - 画弧线









