preface

  • from<from>Submit, to theajax, the front and back end interactions become more flexible and comfortable, and then JQ’s$ajaxaxiosWe seem to be writing more and more easily
  • But more and more, I forgetajaxWhat was it? What did he look like? I remember him, but I don’t really know what he is, exceptajaxfetchWhat is it?
  • This time, let me review the front and back side of the interaction
  • If you want to see the Demo directly here ~ Demo
  • Complete album Demo – album

ajax

What is the

  • Ajax is “Asynchronous Javascript And XML”
  • It is not a new language, but a new way of using existing technical standards
  • It can exchange data with the server and update parts of a web page without reloading the entire page
  • By exchanging a small amount of data with the server in the background,ajaxWeb pages can be asynchronously updated

The basic use

  • Ajax is based on XMLHttpRequest objects
  • Create an XMLHttpRequest object
let xhr = new XMLHttpRequest();
Copy the code
  • Configure request Parameters
  • Synchronization will cause code blocking, and the next operation can be carried out only after the data interaction is completed (success, timeout, failure, etc.). Users will feel sluggish, and the user experience is not good. Asynchronous is generally used (you can adjust the browser network speed to see the effect).
xhr.open('get'.'/checkUserName'.true); // True: asynchronous false: synchronous
Copy the code
  • Receive returned value
  • The return value will bexhr.responseTextpresent
xhr.onload = function () {
    console.log(this.responseText)
}
Copy the code
  • Send to the server
xhr.send();
Copy the code

xhr.open(method, url, async)

  • Specifies the configuration for sending requests to the server

    1. Method – The type of request; Get or post
    2. Url – location of the file on the server – address of the requested data
    3. Async – Whether asynchronous processing is adopted – true: synchronous; False: asynchronous
  • Get and Post pay attention

    • Compared to POST, GET is simpler and faster, and works in most cases
    • However, use a POST request in the following cases:
      • Unable to use cached files (updating files or databases on the server)
      • Sending large amounts of data to the server (POST has no data limit)
      • POST is more stable and reliable than GET when sending user input that contains unknown characters

To send data

URL and the cords

  1. queryString
    • The general form is? key=val
    • If there are multiple parameters, pass&Splicing, as in:? key1=val1&key2=val2
  2. params
    • node - KoaRouterThe back-end is expressed as/get/:keyIn order to:said
    • The front end is appended to the URL/val
    • Such as multiple parameters, back end:/get/:key1/:key2; Front end:/val1/val2
  • queryStringparamsPay attention to the point
    • Choose to usequeryStringorparamsIn fact, you can choose either route, depending on the route design
    • And it’s worth notingfunctionThe same as the passage of the
      • If it isparamsEven if the previous parameter is not needed, it needs to be occupied, for example:/val1/val2.val1Use placeholders when you don’t need them
      • whilequeryStringYou don’t have to say which parameter you want to pass, you just write the corresponding parameterkey=valIt is ok
    • paramsIf the dynamic route is configured without parameters, the request fails. For example:
    • The backend:get/:key
    • The front end must request:/get/valSuch as a direct request/getThe request fails
    • How the URL is transmitted to participate in the requestgetpostRegardless, both request methods can carry parameters in the URL

xhr.send()

  • Parameters can be carried when a request is sent to the server

  • This method is only used for POST

  • You need to set the HTTP header format when sending data

    • Request header type and<from>The form ofenctypeIs essentially the same
    1. text/plain– Does not write the body header format – tostringTo send
    2. application/x-www-form-urlencoded– Send with default encoding
      • It’s written like thisqueryStringBut no?In order to&To connect
    xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
    xhr.send(`key1=val1&key2=val2`); // -> { key1: 'val1', key2: 'val2' }
    Copy the code
    1. multipart/form-data– Send in binary code – Mostly used to send files and other contents:FromData
    2. application/json– tojsonEncode to send
    xhr.setRequestHeader('Content-Type'.'application/json');
    xhr.send(JSON.stringify({
        key1: 'val1'.key2: 'val2'
    }));
    // -> { key1: 'val1', key2: 'val2' }
    Copy the code

Return information -XMLHttpRequest.response

  • Get return header information

    1. xhr.getAllResponseHeaders()– Get all the information
    2. xhr.getResponseHeader()– Obtain the specified information, for example:xhr.getResponseHeader('Content-Type')
  • Get return text

    1. xhr.response– getArrayBuffer,Blob,Document,ObjectDOMStringForm of response data
    2. xhr.responseText– Gets the response data in string form
    3. xhr.responseXML– Gets the response data in XML form
    4. xhr.responseURL– Get the serialized URL
      • Returns an empty string if the URL is empty
      • If the URL has an anchor, the content after the URL # is deleted
      • If the URL is redirected,responseURLThe value of will be the final URL after multiple redirects
  • Note:

    • Retrieving the return body requires that the response header be properly written in the backgroundContent-Type
    • Such as the background response headerContent-TypeYou can rewrite the front end if it’s not written or if it’s written incorrectly
    xhr.overrideMimeType() / / rewrite the content-type
    Copy the code

FromData

  • The FormData object is used to compile data into key-value pairs for useXMLHttpRequestTo send data
  • It is mainly used to send form data, but can also be used to send keyed data independently of the form
  • If the formenctypeAttribute is set tomultipart/form-data, forms will be usedsubmit()Method to send data, thus sending data in the same form
const form = new FormData();
// FormData object can add multiple keys, the first key is input[type=file] files[0]
form.append('img', file);
form.append('name'.'images');

const xhr = new XMLHttpRequest();
xhr.open('post'.'/upload'.true);
xhr.send(form); // Submit the text in send()
Copy the code

Ajax properties and event hooks

  1. xhr.readyState(read only) – Returns an unsigned short integer (unsigned short) number representing the status code of the request
value state describe
0 UNSENT The proxy is created, but the open() method has not yet been called.
1 OPENED open()Method has been called.
2 HEADERS_RECEIVED send()The method has been called, and the header and state are available.
3 LOADING Download;responseTextProperty already contains some data.
4 DONE The download operation is complete.
  1. xhr.status– returnXMLHttpRequestNumeric status code in response
The HTTP status code describe
100 To continue. Continue to respond to the rest of the submission request
200 successful
301 Permanently move. Requests that the resource be permanently moved to a new location
302 Temporary move. Move to new location when requesting resource zero
304 Unmodified. The requested resource has not been modified compared to the last time, and the response does not contain the resource content
401 Unauthorized, requires authentication to disable. Request denied
403 Is prohibited. Request denied
404 The server did not find the required resource
500 Server internal error. The server encountered an error and could not complete the request
503 The server is unavailable. The temporary service is overloaded and cannot process the request
  1. xhr.onreadystatechange– when thereadyStateTriggered when a property changes
    • This method should not be used for synchronized Requests objects
    • When aXMLHttpRequestThe request isabort()When the method is cancelled, its correspondingreadystatechangeThe event will not be triggered
const xhr = new XMLHttpRequest();
xhr.open('post'.'/demo'.true);
xhr.onreadystatechange = function () {
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        console.log(this.responseText);
    }
}
xhr.send();
Copy the code
  1. xhr.timeOut– Maximum request time (ms)
    • An unsigned long integer (unsigned long) digital
    • If this time is exceeded, the request is terminated automatically
  2. XMLHttpRequestEventTarget.ontimeout– called when the request times outEventHandler
  3. xhr.uploadReturns a XMLHttpRequestUploadObject that represents the progress of the upload
The event The information type of the corresponding attribute
onloadstart To get started
onprogress Data transfer in progress

Event. total: indicates the total size to be transmitted

Event. loaded: indicates the size of the uploaded file
onabort Fetch operation terminated
onerror For failure
onload To be successful
ontimeout The fetch operation did not complete within the time specified by the user
onloadend Obtaining completion (successful or not)

The sample

Demo

PS: I have been working recently ~ I will add other information when I am free