What is AJAX

Async javascript and XML at this point refers to local refresh. At the beginning, when the front and back end are not completely separated, the page rendering is mainly server rendering: The client sends a request to the server based on the URL. The server renders the page (structure, style, data) and returns the entire page to the client. However, if the data content is updated, the server needs to change it again, and the browser gets the latest code and can only see the latest content by refreshing the entire page, which is called global refresh

Second, AJAX basic operations

  • Create an XHR object (AJAX instance)
let xhr = new XMLHttpRequest;
//XMLHttpRequest: Fetch XML data from the server based on an HTTP request
Copy the code
  • Open request address
xhr.open('get'.'./data.json');
// XHR ([method], [url], [async default true], [username], [userpass])

Xhr.setrequestheader (' XXX ', 'XXX ') */

/* Request mode: GET features: generally considered to GET information from the server (of course, also can pass the client information to the server), weight: give less, take more - get-head: only need to GET the information of the response header, the body of the response is not accepted (server does not need to return) -delete: This is used when you want to delete some files or a large amount of information on the server. Before sending a normal request, we will send an OPTIONS request to verify the normal connection between the client and the server. POST features: It is generally considered to push information to the server (of course, the server can also return information to the client), proportion: give more, take less - post-put: As opposed to delete, it is usually used to transfer files or big data (such as content edited by a text editor) to the server. The official document does not specify the difference between GET and POST, but it is generally used in the following ways: - Get request sends information to the server based on the URL question mark. - POST request sends information to the server based on the "request body". - The client can also send some brief information to the server based on the set request header (cookie, token,...). The differences between GET and POST are as follows: 1. The information sent by GET to the server is much less than that sent by POST. 2KB (2*1024B), content beyond the limit of the browser will be automatically cut out. Theoretically, there is no limit on the length of post (there is no limit on the size of the request body), but in real projects, in order to ensure the high efficiency of data transmission, we will manually set the limit 2. Security problem: Post is safer than GET. Reason: THE DATA transmitted by GET based on URL is easily hijacked by URL, which is not secure. Post is relatively secure, but not completely secure, so manual encryption (MD5 encryption, etc.) is required for transmission of important information. If the address and parameter of the two get requests are the same, the browser will set the cache of the request itself (of course, this cache is not desired). To avoid using the cache of the browser, we need to ensure that the URL of each request is not exactly the same. Xhr.open ('GET', './data.json? xx=xx&_='+Math.random()) */

Copy the code
  • Listen for the progress of requests as ajax state changes
xhr.onreadystatechange = function(){ 
    if(xhr.readyState === 4 && /^2\d{2}$/. The test (XHR. Status)) {- get response header information XHR. GetAllResponseHeaders (); Xhr.responsetext xhr.responsexml xhr.response xhr.responseType}}/* Get ajax status :xhr.readyState - 2 response header returns - 4 response body returns xhr.status Not all requests are successful, the network status code records this result */
Copy the code
  • Send the request
Xhr.send ([request body information]) xhr.send(JSON.stringfy({
    name: 'xxx'
}))
Copy the code

AJAX state

  • DONE: 4 The response body information is also returned
  • LOADING: 3 The response body is returning from LOADING
  • HEADERS_RECEIVED: 2 The server has returned a response header
  • OPENID: 1 is enabled and OPEN is executed
  • UNSENT: 0 Is not sent. The default state is 0 when XHR is created

HTTP network status code: xhr.status

  • Start with 2:200 The service returns data normally (the client sends a request to the server, and the server returns data to the client normally, but not necessarily as expected)

  • Starts with 3:304 — reads the negotiated cache; 301 — Permanent Redirection (usually used for domain name transfer) 302/307 — Temporary redirection or temporary redirection (usually used for server load balancing)

  • 400 — wrong request parameters 401 — no access 403 — server refused to execute 404 — wrong address

  • Start with 5 (error is usually a server problem) 500 – unknown server error 503 – overload

    The so-called request success or failure in a project falls into two categories:

    1. Network layer: The server does not return any information (or is not connected to the server), [different reasons can be analyzed according to different status codes]
    2. At the business level: Data has been obtained from the server, which does not meet the requirements of the service logic or can be defined as failure. Generally, data returned by the server contains the code identifier to indicate the success or failure of the service logic. (The data identifier needs to be negotiated by the front and back ends)

Summarize XHR attributes and methods and events

  • Xhr.response/xhr.responsetext (returns the result as a string)/xhr.responsexml
  • xhr.status / xhr.statusText
  • Xhr. withCredentials Specifies whether resource credentials are allowed in cross-domain resource requests
  • Xhr.onabort () Is triggered by a request interrupt
  • Xhr.onerror () failed to load
  • xhr.onload()
  • xhr.onloadend()
  • xhr.onloadstart()
  • Xhr.onprogress () is used to upload files and display the loading progress
  • Xhr. upload When the file is uploaded and downloaded
  • xhr.onreadystatechange()
  • Xhr. timeout Sets the timeout event
  • xhr.getAllResponseHeaders()
  • xhr.getResponseHeader([key])
  • xhr.open()
  • xhr.overrideMimeType()
  • xhr.send()
  • xhr.setRequestHeader()