当前位置:网站首页>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! !
边栏推荐
- A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews
- QT meta object qmetaobject indexofslot and other functions to obtain class methods attention
- Aurora system model of learning database
- 【毕业季·进击的技术er】再见了,我的学生时代
- The latest tank battle 2022 full development notes-1
- [the Nine Yang Manual] 2022 Fudan University Applied Statistics real problem + analysis
- 7-11 机工士姆斯塔迪奥(PTA程序设计)
- 简述xhr -xhr的基本使用
- [中国近代史] 第五章测验
- 强化学习系列(一):基本原理和概念
猜你喜欢
一段用蜂鸣器编的音乐(成都)
Change vs theme and set background picture
Mortal immortal cultivation pointer-1
使用Spacedesk实现局域网内任意设备作为电脑拓展屏
MySQL事务及实现原理全面总结,再也不用担心面试
深度强化文献阅读系列(一):Courier routing and assignment for food delivery service using reinforcement learning
5.MSDN的下载和使用
Difference and understanding between detected and non detected anomalies
[hand tearing code] single case mode and producer / consumer mode
【VMware异常问题】问题分析&解决办法
随机推荐
7. Relationship between array, pointer and array
Detailed explanation of redis' distributed lock principle
Redis的两种持久化机制RDB和AOF的原理和优缺点
简单理解ES6的Promise
MATLAB打开.m文件乱码解决办法
实验九 输入输出流(节选)
It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan
Inaki Ading
Have you encountered ABA problems? Let's talk about the following in detail, how to avoid ABA problems
[modern Chinese history] Chapter V test
稻 城 亚 丁
[the Nine Yang Manual] 2019 Fudan University Applied Statistics real problem + analysis
ArrayList的自动扩容机制实现原理
Floating point comparison, CMP, tabulation ideas
Wei Pai: the product is applauded, but why is the sales volume still frustrated
4. Branch statements and loop statements
受检异常和非受检异常的区别和理解
[during the interview] - how can I explain the mechanism of TCP to achieve reliable transmission
[au cours de l'entrevue] - Comment expliquer le mécanisme de transmission fiable de TCP
Using qcommonstyle to draw custom form parts