1. Introduction
The XMLHttpRequest (XHR) object is used to interact with the server. XMLHttpRequest is the core of Ajax technology. Through XMLHttpRequest, you can request a specific URL and get data without refreshing the page. This allows web pages to update partial content of the page without affecting user operations.
XMLHttpRequest can be used to fetch any type of data, not just XML. It even supports protocols other than HTTP (including file:// and FTP), although perhaps more limited for security reasons.
Two, attributes
readyState
Value, read-only attribute, indicating the status code of the request, the specific value is as follows
value | state | describe |
---|---|---|
0 | UNSENT | Indicates that the object was created, but open() the method has not yet been called |
1 | OPENED | Indicates that open() the method has been called |
2 | HEADERS_RECEIVED | Indicates that send() the method has been invoked and the header and state are available |
3 | LOADING | responseText Indicates that the attribute already contains some data during data reception |
4 | DONE | Indicates that data reception has been completed |
onreadystatechange
A writable property expecting a readystatechange
function to be used as the handler for the event. This function is called when readyState
the value of the property changes.
Note 1: This method should not be used for synchronous XMLHttpRequest requests.
Note 2: When the XMLHttpRequest request is abort()
canceled by the method, readystate
it will be set to 0, and the corresponding readystatechange
event will not be triggered at this time.
responseType
String, read-only attribute, used to set the response body type of the request, the expected values are as follows.
value | describe |
---|---|
empty string | Equivalent to the default text |
text | expects the request's response body to return a string |
Jos | Expect the response body of the request to return a JavaScript object created by parsing the received data content into JSON |
arraybuffer | Expects the request's response body to return a JavaScript ArrayBuffer containing binary data |
blob | The response body of the expected request returns a Blob object containing binary data |
document | Expect the response body of the request to return an HTML Document or XML XMLDocument, the specific type depends on the MIME type of the received data |
Note 1: responseType
It needs to be set open()
after the method call and send()
before the method call .
Note 2: A synchronous XMLHttpRequest request cannot modifyresponseType
the value.
Note 3: When the response body type actually sent by the serverresponseType
does not match the type set, the request body will be null.
response
A read-only attribute, representing the response body of the request, whose value type is responseType
determined by the attribute.
Note: When responseType
the value of is an empty string or , when the value of the attribute is 3, the data obtained by the request so far can be read through the attribute. In all other cases, for incomplete or unsuccessful requests, both are .'text'
readyState
response
response
null
responseText
A string, a read-only attribute, representing the text returned by the server after the request is sent.
Note 1: send()
When the method is not called, responseText
it is an empty string; when the request fails, responseText
it is null
.
Note 2: Same response
as the attribute, when readyState
the value of the attribute is 3, responseText
it returns the text content of the server response so far; when readyState
it is 4 and status
the attribute is 200, responseText
it returns all the data of the backend response.
status
Value, read-only property, returns the numeric status code of the server response.
Note 1:status
The value is 0 before the request is completed or when an XMLHttpRequest error occurs .
Note 2: If the status code is not explicitly specified in the service response, it will be 200 by default.
statusText
String, read-only attribute, returns the text information corresponding to the server response status code.
Note 1: If readyState
the value of is 0 or 1, this statusText
returns an empty string.
Note 2: If not explicitly specified in the service response, it defaults to OK.
timeout
A writable attribute, expecting to get a positive integer, indicating the maximum number of milliseconds for the request. After the timeout, the request will be automatically terminated and a timeout event will be triggered.
Note 1: The default value is 0, which means no timeout.
Note 2: In IE, the timeout property may only be set after calling open()
the method and before calling send()
the method.
ontimeout
Writable property, expected to get a function, used as a handler for the request timeout event.
Note:timeout
Timeout events may only occur if the property is set .
upload
A read-only property that returns an XMLHttpRequestUpload
object that represents the progress of the upload, and its progress can be tracked by binding events to it.
The following events can upload
be bound to the property, and the triggering order is from top to bottom.
Note: IE 10 and below are not supported.
event | describe |
---|---|
onloadstart | Fired when the upload starts |
onprogress | Triggered periodically during data transmission, the upload progress can be obtained in this event |
onabort | Triggered when the upload is terminated, xhr.abort() the upload can be terminated by the method. |
onerror | Triggered when the upload fails |
onload | Triggered when the upload is successful |
ontimeout | Fired when the upload timed out, same as the request timed out, but triggered before the request timed out |
onloadend | Triggered when the upload finishes, whether successful or not |
Note: After calling the xhr.abort() method to terminate the upload, the , , , , events will be triggered in sequence xhr.onreadystatechange
xhr.upload.onabort
xhr.upload.onloadend
xhr.onabort
xhr.onloadend
sample code
const xhr = new XMLHttpRequest();
// xhr.timeout = 1000; // 设置了 timeout 才有可能请求超时
xhr.upload.onprogress = (e) => {
if (e.total > 0) {
// 获取进度
console.log(parseInt((e.loaded / e.total) * 100, 10));
}
};
xhr.upload.onloadstart = (e) => {
console.log("上传开始", e);
};
xhr.upload.onabort = (e) => {
console.log("上传终止", e);
};
xhr.upload.onerror = (e) => {
console.log("上传失败", e);
};
xhr.upload.onload = (e) => {
console.log("上传成功", e);
};
xhr.upload.ontimeout = (e) => {
console.log("上传超时", e);
};
xhr.upload.onloadend = (e) => {
console.log("上传结束", e);
};
xhr.ontimeout = (e) => {
console.log("请求超时", e);
};
xhr.open("post", "http://127.0.0.1:8888/test");
xhr.send(formData);
withCredentials
Writable attribute, Boolean value, used to specify whether cross-domain Access-Control requests should carry authorization information, such as cookie or authorization header.
3. Method
open()
Description : Used to initiate an http request. When the object that has already called this method xhr
calls this method again, it is equivalent to calling abort()
the method .
Parameters :(method, url[, async[, name[, password]]])
- method
string, indicating the HTTP method to use, such asGET
, ,POST
etc. For non-HTTP(S) URLs, this parameter is ignored. - A url
string representing the URL to send the request to. - async
Boolean value, optional, indicating whether to send the request asynchronously, the default value is true. When false, the send() method will block until the request is complete. - user
is optional, indicating the user name, used for authentication, and the default is null. - password
is optional, indicating the password, used for authentication, and the default is null.
setRequestHeader()
Description : Set the value of the HTTP request header. The method must be called open()
after and send()
before setRequestHeader()
.
Parameters :(header, value)
- header
The name of the request header attribute. - value
The value of the request header attribute.
send()
Description : Used to send HTTP requests. When the request method is GET
or HEAD
, the parameter should be null
.
Parameters :(body)
- body
is optional, the default isnull
, the type can beDocument
,Blob
,ArrayBufferView
,FormData
,URLSearchParams
, or string.
getResponseHeader()
Description : Gets a string containing the specified response header text.
Parameters :(name)
- name
is a string representing the response header attribute, case-insensitive .
Return value : The value of the response header attribute, in UTF encoding .
Note 1 : If the request has not returned the response header, or the response header attribute does not exist, or is restricted by W3C, returnnull
.
Note 2 :readyState
When the value of the attribute is2
, that is,HEADERS_RECEIVED
when the status is , it means that the response header has been returned.
getAllResponseHeaders()
Description : Get all response headers to \r\n
split the string.
Parameters : none
Return value : String, all response headers, returned when there is no response null
.
Note : In fact, not all response headers can be obtained, and some response headers need to be allowed by the server before they can be obtained. For example, when downloading a fileContent-Disposition
, the backend needs to set the response headerAccess-Control-Expose-Headers : 'Content-Disposition'
. Access-Control-Expose-Headers
You can set the response headers that the client is allowed to access, and its value is the response header name separated by commas.
abort()
Description : Immediately terminate the sent request. When a request is terminated, its readyState will be set to 0 (the event will not be triggered at this time onreadystatechange
), and the status of the request will also be set to 0.
Note : After callingabort()
the method,xhr
the following events will be triggered on the object in sequence:readystatechange
(at this timereadyState
is 4),abort
(at this timereadyState
is 0) andloadend
.
overrideMimeType()
Description : Overwrite the MIME type returned by the server, this method is rarely used.
Parameters :(mimeType)
- mimeType
string, specifies a specific MIME type to replace the MIME type specified by the server, if the server does not specify a type, then XMLHttpRequest will default to it"text/xml"
.
Scenario example : Mandatory stream processing for "text/xml"
data whose response type is type.
4. Events
The following events can be bound to event callbacks through xhr.addEventListener('eventName', handleFun)
or corresponding event properties ( ).no*
event name | trigger timing | illustrate |
---|---|---|
readystatechange | Fired when readyState the value of the property changes |
abort() method will readyState set to 0, but this change does not fire readystatechange the event |
abort | Fired when the request is stopped, such as abort() after calling the method |
- |
error | Triggered when a request fails | Only fires if there is an error at the network level (eg no network). If the error occurs only at the application layer (such as sending an HTTP error code), this event will not be triggered . |
load | Fired when the request completes successfully | load and error is the opposite event, error if it is not triggered, load it will be triggered |
loadstart | Triggered when the request receives response data | This event also applies to <img> and <video> elements; fires before readyState when becomes 3readystatechange |
loadend | Fired when the request ends | Whether the request succeeds (load) or fails (abort or error) |
progress | Triggered periodically when the request receives more data | - |
timeout | Triggered when the request times out | timeout The event may only be triggered if the property is set |