XMLHttpRequest object

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 responseTextIndicates 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 readystatechangefunction to be used as the handler for the event. This function is called when readyStatethe 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, readystateit will be set to 0, and the corresponding readystatechangeevent 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 modifyresponseTypethe value.
  Note 3: When the response body type actually sent by the serverresponseTypedoes 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 responseTypedetermined by the attribute.

  Note: When responseTypethe 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'readyStateresponseresponsenull

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, responseTextit is an empty string; when the request fails, responseTextit is null.
  Note 2: Same responseas the attribute, when readyStatethe value of the attribute is 3, responseTextit returns the text content of the server response so far; when readyStateit is 4 and statusthe attribute is 200, responseTextit 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 readyStatethe value of is 0 or 1, this statusTextreturns 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 XMLHttpRequestUploadobject that represents the progress of the upload, and its progress can be tracked by binding events to it.
  The following events can uploadbe 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.onabortxhr.upload.onloadendxhr.onabortxhr.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 xhrcalls 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 as GET, , POSTetc. 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 GETor HEAD, the parameter should be null.

Parameters :(body)

  • body
    is optional, the default is null, the type can be Document, 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 :readyStateWhen the value of the attribute is2, that is,HEADERS_RECEIVEDwhen the status is , it means that the response header has been returned.

getAllResponseHeaders()

Description : Get all response headers to \r\nsplit 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-HeadersYou 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,xhrthe following events will be triggered on the object in sequence:readystatechange(at this timereadyStateis 4),abort(at this timereadyStateis 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 readyStatethe value of the property changes abort()method will readyStateset to 0, but this change does not fire readystatechangethe 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 loadand erroris the opposite event, errorif it is not triggered, loadit will be triggered
loadstart Triggered when the request receives response data This event also applies to <img>and <video>elements; fires before readyStatewhen 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 timeoutThe event may only be triggered if the property is set

Guess you like

Origin blog.csdn.net/dark_cy/article/details/124437490