preface
- from
<from>
Submit, to theajax
, the front and back end interactions become more flexible and comfortable, and then JQ’s$ajax
、axios
We seem to be writing more and more easily - But more and more, I forget
ajax
What was it? What did he look like? I remember him, but I don’t really know what he is, exceptajax
,fetch
What 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,
ajax
Web 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 be
xhr.responseText
present
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
- Method – The type of request; Get or post
- Url – location of the file on the server – address of the requested data
- 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
queryString
- The general form is
? key=val
- If there are multiple parameters, pass
&
Splicing, as in:? key1=val1&key2=val2
- The general form is
params
node - KoaRouter
The back-end is expressed as/get/:key
In 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
queryString
和params
Pay attention to the point- Choose to use
queryString
orparams
In fact, you can choose either route, depending on the route design - And it’s worth noting
function
The same as the passage of the- If it is
params
Even if the previous parameter is not needed, it needs to be occupied, for example:/val1/val2
.val1
Use placeholders when you don’t need them - while
queryString
You don’t have to say which parameter you want to pass, you just write the corresponding parameterkey=val
It is ok
- If it is
params
If the dynamic route is configured without parameters, the request fails. For example:- The backend:
get/:key
- The front end must request:
/get/val
Such as a direct request/get
The request fails - How the URL is transmitted to participate in the request
get
和post
Regardless, both request methods can carry parameters in the URL
- Choose to use
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 ofenctype
Is essentially the same
text/plain
– Does not write the body header format – tostring
To sendapplication/x-www-form-urlencoded
– Send with default encoding- It’s written like this
queryString
But no?
In order to&
To connect
- It’s written like this
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded'); xhr.send(`key1=val1&key2=val2`); // -> { key1: 'val1', key2: 'val2' } Copy the code
multipart/form-data
– Send in binary code – Mostly used to send files and other contents:FromDataapplication/json
– tojson
Encode to send
xhr.setRequestHeader('Content-Type'.'application/json'); xhr.send(JSON.stringify({ key1: 'val1'.key2: 'val2' })); // -> { key1: 'val1', key2: 'val2' } Copy the code
- Request header type and
Return information -XMLHttpRequest.response
-
Get return header information
xhr.getAllResponseHeaders()
– Get all the informationxhr.getResponseHeader()
– Obtain the specified information, for example:xhr.getResponseHeader('Content-Type')
-
Get return text
xhr.response
– getArrayBuffer
,Blob
,Document
,Object
或DOMString
Form of response dataxhr.responseText
– Gets the response data in string formxhr.responseXML
– Gets the response data in XML formxhr.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,
responseURL
The 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 background
Content-Type
- Such as the background response header
Content-Type
You 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
- Retrieving the return body requires that the response header be properly written in the background
FromData
- The FormData object is used to compile data into key-value pairs for use
XMLHttpRequest
To 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 form
enctype
Attribute 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
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;responseText Property already contains some data. |
4 | DONE |
The download operation is complete. |
xhr.status
– returnXMLHttpRequest
Numeric 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 |
xhr.onreadystatechange
– when thereadyState
Triggered when a property changes- This method should not be used for synchronized Requests objects
- When a
XMLHttpRequest
The request isabort()
When the method is cancelled, its correspondingreadystatechange
The 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
xhr.timeOut
– Maximum request time (ms)- An unsigned long integer (
unsigned long
) digital - If this time is exceeded, the request is terminated automatically
- An unsigned long integer (
XMLHttpRequestEventTarget.ontimeout
– called when the request times outEventHandler
xhr.upload
– Returns aXMLHttpRequestUpload
Object 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