当前位置:网站首页>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! !
边栏推荐
- [modern Chinese history] Chapter 6 test
- [hand tearing code] single case mode and producer / consumer mode
- 3. Input and output functions (printf, scanf, getchar and putchar)
- Mortal immortal cultivation pointer-2
- Miscellaneous talk on May 27
- 7-9 制作门牌号3.0(PTA程序设计)
- 6. Function recursion
- 仿牛客技术博客项目常见问题及解答(一)
- Miscellaneous talk on May 14
- Cookie和Session的区别
猜你喜欢
A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews
2.C语言初阶练习题(2)
It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan
1. Preliminary exercises of C language (1)
6. Function recursion
Safe driving skills on ice and snow roads
这次,彻底搞清楚MySQL索引
4. Binary search
【手撕代码】单例模式及生产者/消费者模式
Pit avoidance Guide: Thirteen characteristics of garbage NFT project
随机推荐
String abc = new String(“abc“),到底创建了几个对象
[modern Chinese history] Chapter 9 test
1. First knowledge of C language (1)
扑克牌游戏程序——人机对抗
[the Nine Yang Manual] 2022 Fudan University Applied Statistics real problem + analysis
(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。
C language Getting Started Guide
Redis cache obsolescence strategy
ABA问题遇到过吗,详细说以下,如何避免ABA问题
7-14 错误票据(PTA程序设计)
4. Binary search
Write a program to simulate the traffic lights in real life.
2022 Teddy cup data mining challenge question C idea and post game summary
20220211-CTF-MISC-006-pure_ Color (use of stegsolve tool) -007 Aesop_ Secret (AES decryption)
Wechat applet
Implementation of count (*) in MySQL
canvas基础2 - arc - 画弧线
Why use redis
【九阳神功】2017复旦大学应用统计真题+解析
实验八 异常处理