当前位置:网站首页>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! !
边栏推荐
- 20220211-CTF-MISC-006-pure_ Color (use of stegsolve tool) -007 Aesop_ Secret (AES decryption)
- 3. Input and output functions (printf, scanf, getchar and putchar)
- Leetcode.3 无重复字符的最长子串——超过100%的解法
- Redis实现分布式锁原理详解
- The difference between overloading and rewriting
- 3. C language uses algebraic cofactor to calculate determinant
- 7-3 构造散列表(PTA程序设计)
- 2022泰迪杯数据挖掘挑战赛C题思路及赛后总结
- 杂谈0516
- The difference between cookies and sessions
猜你喜欢

This time, thoroughly understand the MySQL index

20220211-CTF-MISC-006-pure_ Color (use of stegsolve tool) -007 Aesop_ Secret (AES decryption)

C language Getting Started Guide

FAQs and answers to the imitation Niuke technology blog project (II)

It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan

强化学习系列(一):基本原理和概念

8. C language - bit operator and displacement operator

Using spacedesk to realize any device in the LAN as a computer expansion screen

仿牛客技术博客项目常见问题及解答(二)

3. C language uses algebraic cofactor to calculate determinant
随机推荐
【九阳神功】2022复旦大学应用统计真题+解析
3. Number guessing game
[the Nine Yang Manual] 2020 Fudan University Applied Statistics real problem + analysis
深度强化文献阅读系列(一):Courier routing and assignment for food delivery service using reinforcement learning
【VMware异常问题】问题分析&解决办法
2. First knowledge of C language (2)
实验六 继承和多态
Floating point comparison, CMP, tabulation ideas
(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。
String ABC = new string ("ABC"), how many objects are created
2. Preliminary exercises of C language (2)
[graduation season · advanced technology Er] goodbye, my student days
实验七 常用类的使用(修正帖)
Zatan 0516
Write a program to simulate the traffic lights in real life.
A piece of music composed by buzzer (Chengdu)
TypeScript快速入门
8. C language - bit operator and displacement operator
JS interview questions (I)
Have you encountered ABA problems? Let's talk about the following in detail, how to avoid ABA problems