当前位置:网站首页>Brief introduction to XHR - basic use of XHR

Brief introduction to XHR - basic use of XHR

2022-07-06 13:49:00 Ling Xiaoding


XMLHttpRequest API summary

attribute :

  1. readyState xhr The status code 4 The response body is received
  2. status Get status code
  3. responseText Get the response body , Text format
  4. responseXML Get the response body ,xml Format
  5. onreadtstatechange event , When xhr.readyState Triggered by property change
  6. onload event , Response received

Method :

  1. open(method, url, async) Set the mode of request , The path of the request , Sync / asynchronous
  2. send(requestBody) Send request body
  3. setRequestHeader(key, value) Set request header
  4. getResponseHeader(key) Get response header

How to request

onload: Easy to get the response events

GET

  1. establish xhr object
  2. call open Method , Set the request mode and URL
  3. call send Method , send out
  4. When the request response process is over ( Called xhr.onload event ), adopt responseText Property to receive the data returned by the server
  5. ajax Of get 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

  1. establish xhr object
  2. call open Method , Set the request mode and URL
  3. call setRequestHeader( ) Method , Set up header head , Appoint content-type
  4. call send Method , send out
  5. 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

  1. ajax Of GET Request and ajax Of post request , The position of passing parameters is different
  2. GET The request can only carry a small number of parameters ,POST There is no limit to the data carried by the request
  3. 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
0UNSENT agent (XHR) Be created , But not yet called open() Method
1OPENEDopen() Method has been called , It establishes the connection .
2HEADERS_RECEIVEDsend() Method has been called , And you can get the status line and the response header .
3LOADING Response body downloading ,responseText Property may already contain some data .
4DONE 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

  1. xhr.open( ) The third parameter passes in a Boolean value
  2. The function is to set whether the request is executed asynchronously , The default is true asynchronous ,false For synchronization
  3. Synchronization request
    • ajax Synchronous request , Will be in send The method is stuck there , When did the server return data , Subsequent code can be executed , Disfavor use
    • Asynchronous requests
  4. 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! !

原网站

版权声明
本文为[Ling Xiaoding]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916579659.html