XMLHttpRequest object (AJAX communication)

1.What is the XMLHttpRequest object?

Communication between the browser and the server uses the HTTP protocol. When the user types a URL in the browser address bar or submits content to the server through a web form, the browser will make an HTTP request to the server.

In 1999, Microsoft released IE browser version 5.0, which introduced a new feature for the first time: allowing JavaScript scripts to initiate HTTP requests to the server. This feature did not attract attention at the time. It was not until the release of Gmail in 2004 and Google Map in 2005 that it attracted widespread attention. In February 2005, the word AJAX was officially proposed for the first time. It is the abbreviation of Asynchronous JavaScript and XML, which refers to asynchronous communication through JavaScript, obtaining XML documents from the server, extracting data, and then updating the current web page. corresponding part without refreshing the entire web page. Later, the word AJAX became synonymous with HTTP communication initiated by JavaScript scripts. In other words, as long as a script is used to initiate communication, it can be called AJAX communication. W3C also released its international standards in 2006.

Specifically, AJAX includes the following steps.

  1. Create an XMLHttpRequest instance
  2. Make an HTTP request
  3. Receive data returned by the server
  4. Update web page data

To summarize, in order for the web page to automatically update the data in the web page without refreshing, we need to obtain the data from the back end and display it on the front end page. Then the front-end is responsible for completing communication establishment, data reception, and data display. So the behavior of front-end JS processing HTTP communication is called AJAX (Asynchronous JavaScript and XML). You could also call it Ajax. javascript

Note that the XML here is used as a communication template to provide a unified template when back-end programs in different languages ​​interact with the front-end. It has now been replaced by JSON format, but it still uses the name XML. Therefore AXJX is now used to represent a behavior.

Finally, let’s explain the XMLhttprequest object:XMLHttpRequestThe object is the main interface of AJAX and is used for communication between the browser and the server. Although the name contains XML and Http, it can actually use multiple protocols (such as file or ftp), send data in any format (including string and binary).

1.1 Trying AJAX for the first time

In this section, we try to run an ajax script to experience the feeling of using JS to build HTTP communication on the front end. Note here that AJAX can only make HTTP requests to the same source URL (the protocol, domain name, and port are the same). If a cross-domain request is made, an error will be reported. AJAX only works for same-origin communication.

First create a new web page 01.html, containing a js file inside:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>源页面---</h1>
</body>
<script src="./01.js"></script>
</html>

Create a second web page 02.html as the target of our AJAX access

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>被请求网页:"hello world"</h1>
</body>
</html>

At this time, save the following JS code to the 01.js file:

//XMLHttpRequest本身是一个构造函数,可以使用new命令生成实例。它没有任何参数。
var xhr = new XMLHttpRequest();

//使用事件监听属性监听请求的结果,并在函数内写上对其的操作
xhr.onreadystatechange = function(){
    
    
  // 通信成功时,状态值为4
  if (xhr.readyState === 4){
    
    
    //判断状态码是否为200 OK,否则抛出错误
    if (xhr.status === 200){
    
    
      console.log(xhr.responseText);
    } else {
    
    
      console.error(xhr.statusText);
    }
  }
};

//使用事件监听属性监听error事件,指定状态码错误回显
xhr.onerror = function (e) {
    
    
  console.error(xhr.statusText);
};


//调用实例的open()方法,进行get请求的参数设定,其中第三个请求true的意思是异步进行请求
xhr.open('GET', './03.html', true);
//最后使用send()方法实际发出请求
xhr.send(null);

Test the access effect:
Insert image description here
You can see that in the console there are returned results obtained by accessing the target page through AJAX. It proves that this AJAX communication was successful. When we modify the request page in JS to 03.html, a 404 status code will be echoed.

Insert image description here
So next, we will learn more about the usage of xmlhttprequest.

1.2 Some unclear concepts

1.2.1 The difference between asynchronous requests and synchronous requests

Ajax asynchronous request: An asynchronous request means that the browser can continue to do anything while making the request. Ajax sending the request will not affect the loading of the page and the user's operation. It is equivalent to two lines, each going its own way and interacting with each other. No impact. The general default value is true. Asynchronous requests do not affect the user experience at all. No matter how long or short the request is, the user is concentrating on operating other content on the page and does not feel like waiting.

Ajax synchronous request: A synchronous request means that after the current request is issued, the browser cannot do anything. It must wait until the request is completed and the data is returned before the subsequent code is executed, which is equivalent to queuing. That is to say, when the JS code is loaded into the current When ajax is used, all the code in the page will stop loading, and the page will be in a state of suspended animation. After the ajax is executed, other code pages will continue to run to release the suspended animation state (that is, when ajax returns the data, the subsequent functions will be executed).

It can also be understood that assuming we need to boil water and cook dumplings, then in a synchronous transmission scenario, we must complete the four tasks of boiling water, making dumplings, cooking dumplings, and eating dumplings in sequence. Then under asynchronous requests, we can boil water and make dumplings at the same time. Creating two timelines to complete this task can save time to a certain extent.

1.2.2 A pinch of object-oriented knowledge

1. What is the object?

(1) The object is the abstraction of a single physical object.
A book, a car, and a person can be objects. A database, a web page, and a remote server connection can also be objects. When physical objects are abstracted into objects, the relationship between physical objects becomes the relationship between objects, so that real situations can be simulated and objects can be programmed.
(2) The object is a container that encapsulates properties and methods.
Properties are the state of the object, and methods are the behavior of the object (complete a certain task). For example, we can abstract animals into objects, use "attributes" to record which animal they are, and use "methods" to represent a certain behavior of the animal (running, hunting, resting, etc.) . animal

That is to say, there are two types of important indicators or key points of description for an object, namely the properties and methods of the object. Properties are described parameters, and methods are some behaviors that this object can perform.

2. What is the constructor?

The first step in object-oriented programming is to generate objects. As mentioned earlier, an object is an abstraction of a single physical object. Usually a template is needed to represent the common characteristics of a certain type of physical object, and then the object is generated based on this template.
Typical object-oriented programming languages ​​(such as C++ and Java) have the concept of "class". The so-called "class" is the template of the object, and the object is an instance of the "class". However, the object system of the JavaScript language is not based on "classes", but on constructors and prototype chains.
The JavaScript language uses constructors as templates for objects. The so-called "constructor" is a function specially used to generate instance objects. It is the template of the object, describing the basic structure of the instance object. A constructor can generate multiple instance objects, all of which have the same structure.

The constructor is equivalent to a special function, but it has its own characteristics and usage. Use the new command when creating an object. The first letter of the constructor name is usually capitalized.

After seeing this, you will probably understand that to learn the XMLhttprequest object, you need to have a more systematic understanding of the attributes and methods that can be used by instances created by this object. To strike while the iron is hot, let’s first take a look at the instance properties ofXMLHttpRequest

2.Instance attributes of XMLHttpRequest

2.1 readyState与onreadystatechange

XMLHttpRequest.readyStateReturns an integer representing the current state of the instance object. This property is read-only. It may return the following values.

  • 0, indicates that the XMLHttpRequest instance has been generated, but the instance's open() method has not been called.
  • 1 means that the open() method has been called, but the instance's send() method has not yet been called. You can still use the instance's setRequestHeader()Method, set the header information of the HTTP request.
  • 2, indicating that the instance's send() method has been called, and the header information and status code returned by the server have been received.
  • 3, indicating that the data body (body part) from the server is being received. At this time, if the instance's responseType attribute is equal to text or an empty string, the responseText attribute will contain part of the information that has been received .
  • 4. Indicates that the data returned by the server has been completely received, or the reception has failed.

During the communication process, whenever the status of the instance object changes, the value of its readyState attribute will change. Every time this value changes, thereadyStateChange event will be triggered.

For the XMLHttpRequest.onreadystatechange attribute points to a listener function. Its function is that when the readystatechange event occurs (the instance's readyState attribute changes), the operations within this function will be executed in sequence. In addition, if you use the abort() method of the instance to terminate the XMLHttpRequest request, it will also cause the readyState attribute to change, causing the XMLHttpRequest.onreadystatechange attribute to be called.

Example 1: Verify that each readystate change triggers thereadyStateChange event.

//XMLHttpRequest本身是一个构造函数,可以使用new命令生成实例。它没有任何参数。
var xhr = new XMLHttpRequest();

console.log(xhr.readyState);

//使用事件监听属性监听请求的结果,并在函数内打印出对应的阶段
xhr.onreadystatechange = function(){
    
    
  // 通信成功时,状态值为4
  if (xhr.readyState === 0){
    
    
    console.log("实例已创建");
    console.log(xhr.readyState);
  }
  if (xhr.readyState === 1){
    
    
    console.log("已经调用open()方法");
    console.log(xhr.readyState);
  }
  if (xhr.readyState === 2){
    
    
    console.log("已经调用send()方法,收到信息头部");
    console.log(xhr.readyState);
    console.log(xhr.getAllResponseHeaders());
  }
  if (xhr.readyState === 3){
    
    
    console.log("正在接收数据体");
    console.log(xhr.readyState);
  }
  if (xhr.readyState === 4){
    
    
    console.log("请求接收完毕");
    console.log(xhr.readyState);
    console.log(xhr.responseText);
  }
};

//调用实例的open()方法,进行get请求的参数设定,其中第三个请求true的意思是异步进行请求
xhr.open('get', 'http://127.0.0.1/secbasic/02.html', true);

//最后使用send()方法实际发出请求
xhr.send(null);

Insert image description here

2.2 XMLHttpRequest.response

XMLHttpRequest.responseThe attribute represents the data body returned by the server (i.e., the body part of the HTTP response). It may be any data type, such as string, object, binary object, etc. The specific type is determined by the XMLHttpRequest.responseType attribute. This property is read-only.

If this request is unsuccessful or the data is incomplete, this attribute is equal tonull. However, if the responseType attribute is equal to text or an empty string, before the request ends (the stage where readyState is equal to 3), < The /span>response attribute contains part of the data that has been returned by the server.

Of course, some of the data here means that such partial display will only appear when the delay is relatively large and the request content is relatively large. The local results usually have received the required information at this stage.

2.3 XMLHttpRequest.responseType

XMLHttpRequest.responseTypeThe attribute is a string indicating the type of data returned by the server. This attribute is writable. You can set the value of this attribute after calling the open() method and before calling the send() method to tell the browser how to interpret the returned data. If responseType is set to an empty string, it is equivalent to the default value text.

XMLHttpRequest.responseTypeProperties can be equal to the following values.

  • "" (empty string): Equivalent to text, indicating that the server returns text data.
  • "arraybuffer": ArrayBuffer object, indicating that the server returns a binary array.
  • "blob": Blob object, indicating that the server returns a binary object.
  • "document": Document object, indicating that the server returns a document object.
  • "json": JSON object.
  • "text": string.

Among the above types, text type is suitable for most situations, and it is more convenient to directly process text. The document type is suitable for returning HTML/XML documents. This means that for those websites that turn on CORS, you can directly use Ajax to crawl the web page, and then directly crawl it back without parsing the HTML string. Perform DOM operations on the data. The blob type is suitable for reading binary data, such as image files.

Example 1: JSON object return parameter reception

//后端php页面--- 01.php
<?
//创建数组存储数据
$arr = array('name' => 'batman','age' => '18','money' => '?????');
//调用json_ecode函数将返回值json化
echo json_encode($arr);
//测试JS --- 01.js
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/secbasic/01.php', true);
xhr.responseType = 'json';
xhr.send(null);

xhr.onload = function () {
    
    
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
      //这里不可以在使用固定格式的responsetext会报出类型不匹配的错误
      console.log(xhr.response);
  }
  else{
    
    
    console.error(xhr.status);
  }
};

Insert image description here
Example 2: AJAX request for image files

var xhr = new XMLHttpRequest();
xhr.open('GET', './01.png', true);
xhr.responseType = 'blob';
xhr.send();

xhr.onload = function(e) {
    
    
  if (this.status === 200) {
    
    
    //var blob = new Blob([xhr.response], {type: 'image/png'});
    // 或者
    var blob = xhr.response;
    console.log(blob);
  }
};

Insert image description here

2.4 XMLHttpRequest.responseText

XMLHttpRequest.responseTextProperty returns the string received from the server. This property is read-only. This attribute will contain complete data only after the HTTP request has been received.

Example:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/secbasic/02.html', true);

xhr.responseType = 'text';
xhr.onload = function () {
    
    
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
  //判断状态4,状态码为200时日志打印出此属性
    console.log(xhr.responseText);
  }
};

xhr.send(null);

Insert image description here

2.5 XMLHttpRequest.responseURL

XMLHttpRequest.responseURLThe attribute is a string representing the URL of the server sending the data.

Note that the value of this attribute is not necessarily the same as the request URL specified by the open() method. If a jump occurs on the server side, this attribute returns the last URL that actually returns data. Additionally, if the original URL includes an anchor (fragment), this property will strip the anchor.

Example: Return the URL to which the message was sent after redirection

01.js code content:

//这里使用之前的一段代码,稍加修改
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/secbasic/02.php', true);
xhr.responseType = 'json';
xhr.send(null);

xhr.onload = function () {
    
    
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
      //这里不可以在使用固定格式的responsetext会报出类型不匹配的错误
      console.log(xhr.response);
  }
  else{
    
    
    console.error(xhr.status);
  }
};

Contents of 01.php and 02.php:

//php --- 01.php
<?
//创建数组存储数据
$arr = array('name' => 'batman','age' => '18','money' => '?????');
//调用json_ecode函数将返回值json化
echo json_encode($arr);

//php --- 02.php
<?php
header("location: ./01.php", true, 302);

Insert image description here

2.6 XMLHttpRequest.status and statusText

XMLHttpRequest.statusThe attribute returns an integer representing the HTTP status code responded by the server. Generally speaking, if the communication is successful, this status code is 200; if the server does not return a status code, then this attribute defaults to 200. Before the request is made, this attribute is0. This property is read-only.

  • 200, OK, access is normal
  • 301, Moved Permanently, permanently moved
  • 302, Moved temporarily, temporarily moved
  • 304, Not Modified, not modified
  • 307, Temporary Redirect, temporary redirect
  • 401, Unauthorized, unauthorized
  • 403, Forbidden, access prohibited
  • 404, Not Found, the specified URL was not found
  • 500, Internal Server Error, an error occurred in the server

Basically, there are only 2xx and 304 status codes, indicating that the server returns a normal status.

XMLHttpRequest.statusTextThe attribute returns a string representing the status prompt sent by the server. Unlike the status attribute, this attribute contains the entire status information, such as "OK" and "Not Found". Before the request is sent (that is, before the open() method is called), the value of this attribute is an empty string; if the server does not return a status prompt, the value of this attribute defaults to "OK". This property is read-only.

Example:

var xhr = new XMLHttpRequest();

console.log("调用open()函数之前的xhr.statusText:");
console.log(xhr.statusText);

xhr.open('GET', 'http://127.0.0.1/secbasic/02.html', true);
xhr.responseType = 'json';
xhr.send(null);

xhr.onload = function () {
    
    
  if (xhr.readyState === 4 && xhr.status === 200) {
    
    
      //这里不可以在使用固定格式的responsetext会报出类型不匹配的错误
      console.log("xhr.status:");
      console.log(xhr.status);
      console.log("xhr.statusText:");
      console.log(xhr.statusText);
  }
};

Insert image description here

2.7 XMLHttpRequest.timeout and ontimeout

XMLHttpRequest.timeoutThe property returns an integer indicating how many milliseconds later, if the request still does not get the result, it will be automatically terminated. If this attribute is equal to 0, it means there is no time limit.

XMLHttpRequestEventTarget.ontimeoutThe attribute is used to set a listening function. If a timeout event occurs, this listening function will be executed.

Example:

var xhr = new XMLHttpRequest();
//访问目标URL
var url = 'https://www.google.com';

xhr.ontimeout = function () {
    
    
  console.error('The request for ' + url + ' timed out.');
};

xhr.onload = function() {
    
    
  if (xhr.readyState === 4) {
    
    
    if (xhr.status === 200) {
    
    
      // 处理服务器返回的数据
      console.info(xhr.response);
    } else {
    
    
      console.error(xhr.statusText);
    }
  }
};

xhr.open('GET', url, true);
// 指定 10 秒钟超时
xhr.timeout = 3 * 1000;
xhr.send(null);

Insert image description here

2.8 Event listening properties

The XMLHttpRequest object can specify listening functions for the following events.

  • XMLHttpRequest.onloadstart: Listening function for the loadstart event (HTTP request issued)
  • XMLHttpRequest.onprogress: Listening function for progress event (data is being sent and loaded)
  • XMLHttpRequest.onabort: Listening function for abort event (request aborted, such as the user calling the abort() method)
  • XMLHttpRequest.onerror: Listening function for error event (request failure)
  • XMLHttpRequest.onload: Listening function for the load event (request completed successfully)
  • XMLHttpRequest.ontimeout: Listening function for timeout events (the user-specified time limit has exceeded and the request has not been completed)
  • XMLHttpRequest.onloadend: Listening function for the loadend event (request completion, regardless of success or failure)

progressThe event listening function has an event object parameter, which has three properties: loadedThe property returns the amount of data that has been transmitted,totalThe property returns the total The amount of data, lengthComputable attribute returns a Boolean value indicating whether the loading progress can be calculated. Among all these listening functions, only the listening function for the progress event has parameters, and the other functions have no parameters.

Note that if a network error occurs (for example, the server cannot be connected), the onerror event cannot obtain error information. In other words, there may not be an error object, so only the error message can be displayed.

Among them, commonly used events include onload, ontimeout, onerror, etc.

Example:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/secbasic/02.html', true);
// xhr.open('GET', 'http://www.baidu.com', true);



xhr.onload = function() {
    
    
  var responseText = xhr.responseText;
  console.log(responseText);
  // process the response.
 };
 
 xhr.onabort = function () {
    
    
   console.log('The request was aborted');
 };
 
 xhr.onprogress = function (event) {
    
    
   console.log(event.loaded);
   console.log(event.total);
 };
 
 xhr.onerror = function() {
    
    
   console.log('There was an error!');
 };
 
 xhr.send(null);

Trying to request Baidu's URL across domains, an error was returned:
Insert image description here
Add artificial interruption of communication:
Insert image description here
Test normal request:
Insert image description here

2.9 XMLHttpRequest.upload

XMLHttpRequest can not only send requests, but also send files. This is AJAX file upload. After sending the file, you can get an object through the XMLHttpRequest.upload attribute. By observing this object, you can know the progress of the upload. The main method is to monitor various events of this object: loadstart, loadend, load, abort, error, progress, timeout.

Example:

Insert elements on the 01.html page

<progress min="0" max="100" value="0">0% complete</progress>

Modify the content of 01.js:

//定义上传函数,参数为bloborfile,函数内进行文件上传的操作
function upload(blobOrFile) {
    
    
  var xhr = new XMLHttpRequest();
  xhr.open('POST', './01.php', true);
  xhr.onload = function (e) {
    
    };
  
  //抓取特定标签
  var progressBar = document.querySelector('progress');
  
  //监听上传进度
  xhr.upload.onprogress = function (e) {
    
    
    if (e.lengthComputable) {
    
    
      progressBar.value = (e.loaded / e.total) * 100;
      // 兼容不支持 <progress> 元素的老式浏览器
      progressBar.textContent = progressBar.value;
    }
  };
  xhr.send(blobOrFile);
}

//调用上传函数
upload(new Blob(['hello world'], {
    
    type: 'text/plain'}));

Insert image description here
We can see that the little blue bar is full in no time. Can be used to dynamically display upload progress.

3.Instance methods of XMLHttpRequest

3.1 XMLHttpRequest.open()

XMLHttpRequest.open()The method is used to specify the parameters of the HTTP request, or to initialize the XMLHttpRequest instance object. It can accept a total of five parameters.

void open(
   string method,
   string url,
   optional boolean async,
   optional string user,
   optional string password
);
  • method:Display HTTP behavior, comparisonGET, POST, PUT, DELETE,HEADetc.
  • url: Represents the request to send the target URL.
  • async: Boolean value, indicating whether the request is asynchronous, the default istrue. If set to false, the send() method will not proceed to the next step until the result is received from the server. This parameter is optional. Since synchronous AJAX requests will cause the browser to lose response, many browsers have banned its use in the main thread and only allow it to be used in Worker. Therefore, this parameter should not be set to false.
  • user: Indicates the username used for authentication, the default is an empty string. This parameter is optional.
  • password: Indicates the password used for authentication, the default is an empty string. This parameter is optional.

Note that if you make an AJAX request that has used the open() method, using this method again is equivalent to calling abort(), that is, terminating the request.

3.2 XMLHttpRequest.send()

XMLHttpRequest.send()Method is used to actually make the HTTP request. Its parameters are optional. If there are no parameters, it means that the HTTP request has only one URL and no data body. A typical example is the GET request; if there are parameters, it means that in addition to the header information, it also contains information containing specific data. body, a typical example is a POST request.

Example 1: Example of get request

var xhr = new XMLHttpRequest();
//GET请求的参数,作为查询字符串附加在 URL 后面。
xhr.open('GET',
  'http://www.example.com/?id=' + encodeURIComponent(id),
  true
);
xhr.send(null);

Example 2: POST request sent

//php --- 01.php  直接打印出POST接到的数据
<?var_dump($_POST);
//01.js
var xhr = new XMLHttpRequest();

var username = "batman";
var password = "123456"; 
//拼接请求体数据
var data = 'username='
  + encodeURIComponent(username)
  + '&password='
  + encodeURIComponent(password);


xhr.open('POST', 'http://127.0.0.1/secbasic/01.php', true);
//设置请求头的content-type字段保持与请求体数据类型的一致性
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);

xhr.onload = function() {
    
    
    if(xhr.readyState === 4 && xhr.status === 200){
    
    
      console.log(xhr.response);
    }
};

Insert image description here

3.3 setRequestHeader()

XMLHttpRequest.setRequestHeader()The method is used to set the header information of the HTTP request sent by the browser. This method must be called after open() and before send(). If this method is called multiple times to set the same field, the values ​​from each call will be combined into a single value and sent.

This method accepts two parameters. The first parameter is a string representing the field name of the header information, and the second parameter is the field value.

xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Content-Length', JSON.stringify(data).length);
xhr.send(JSON.stringify(data));

The above code first sets the header informationContent-Type, which means sending data in JSON format; then sets Content-Length, which means the data length; and finally sends the JSON data.

3.4 overrideMimeType()

XMLHttpRequest.overrideMimeType()The method is used to specify the MIME type and override the real MIME type returned by the server, allowing the browser to process it differently. For example, the data type returned by the server is text/xml. Due to various reasons, the browser fails to parse and reports an error. At this time, the data cannot be obtained. In order to get the original data, we can change the MIME type to text/plain, so that the browser will not automatically parse it, so we can get the original text.

xhr.overrideMimeType('text/plain')

Modifying the data type returned by the server is not a method that should be taken under normal circumstances. If you want the server to return a specified data type, you can use the responseType attribute to tell the server which parsing mode to use. Use the overrideMimeType() method only when the server cannot return a certain data type.

3.5 getResponseHeader()

XMLHttpRequest.getResponseHeader()The method returns the value of the specified field in the HTTP header. If no response from the server has been received or the specified field does not exist, null is returned. The parameters of this method are not case sensitive.

function getHeaderTime() {
    
    
  console.log(this.getResponseHeader("Last-Modified"));
}

var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'aimurl');
xhr.onload = getHeaderTime;
xhr.send();

If there are multiple fields with the same name, their values ​​will be concatenated into a string, and each field will be separated by "comma + space".

3.6 getAllResponseHeaders()

XMLHttpRequest.getAllResponseHeaders()The method returns a string representing all HTTP header information sent by the server. The format is a string, and each header information is separated by CRLF (carriage return + line feed). If no response from the server is received, the attribute is null. If a network error occurs, this property is an empty string.

Example: Test the returned request header information

var xhr = new XMLHttpRequest();
xhr.open('GET', './02.html', true);
xhr.send();

xhr.onreadystatechange = function () {
    
    
  if (this.readyState === 4) {
    
    
    var headers = xhr.getAllResponseHeaders();
    console.log(headers);
  }
}

Insert image description here
You can see in the debugging interface that the original data of the header contains newline symbols such as \r\n. It can be replaced:

//01.js
var xhr = new XMLHttpRequest();
xhr.open('GET', './02.html', true);
xhr.send();


xhr.onreadystatechange = function () {
    
    
  if (this.readyState === 4) {
    
    
    var headers = xhr.getAllResponseHeaders();
    console.log(headers);
    //------------字符处理
    //定义数组,将header内的字符串头尾空格去掉后按照换行符进行分割存入数组
    var arr = headers.trim().split(/[\r\n]+/);
    var headerMap = {
    
    };


    //使用数组的循环,初始化一个新的数组类型,以键值对的形态存储返回的headers
    arr.forEach(function (line) {
    
    
      var parts = line.split(': ');
      var header = parts.shift();
      var value = parts.join(': ');
      headerMap[header] = value;
    });

    /*
    函数注解:
    split() 方法用于把一个字符串分割成字符串数组。
    shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。
    join() 方法用于把数组中的所有元素转换一个字符串。元素是通过指定的分隔符进行分隔的。
    */
    //打印结果
    console.log(headerMap);
  }
}

Insert image description here

3.7 XMLHttpRequest.abort()

XMLHttpRequest.abort()The method is used to terminate the HTTP request that has been sent. After calling this method, the readyState attribute changes to 4, and the status attribute changes to 0.

Example: After 5 seconds, terminate an AJAX request.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.example.com/page.php', true);
setTimeout(function () {
    
    
  if (xhr) {
    
    
    xhr.abort();
    xhr = null;
  }
}, 5000);

At this point, this part of the knowledge has been roughly sorted out. In the process of learning code, it is indeed necessary to practice more on its necessary debugging capabilities.

Reference links:

https://www.php.cn/js-tutorial-411396.html The difference between AXJX synchronous transmission and asynchronous transmission
and the teacher’s notes document...

Guess you like

Origin blog.csdn.net/qq_55316925/article/details/128584017