Next Ajax article
***
Ajax advanced
catalogue
Use xhr to initiate GET requests
Understand readyState property of xhr object
Use xhr to initiate GET request with parameters
Use xhr to initiate POST requests
New features of XMLHttpRequest Level2
Basic use of XMLHttpRequest
XMLHttpRequest definition
Definition: it is a JS object provided by the browser. Through it, you can request data resources on the server. The Ajax functions in JQuery learned before are encapsulated based on xhr objects.
Use xhr to initiate GET requests
Steps:
- Create xhr object
- Call the open function
- Call the send function
- Listen for onreadystatechange events
The code is as follows:
<body> <script> // 1. Create XHR object var xhr = new XMLHttpRequest() // 2. Call the open function xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks') // 3. Call the send function xhr.send() // 4. Listen to onreadystatechange event xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // Get the data of the server response console.log(xhr.responseText) } } </script> </body>
Understand readyState property of xhr object
The readyState attribute of the xhr object is used to represent the state of the current Ajax request.
Status of each Ajax request:
Use xhr to initiate GET request with parameters
When launching a GET request with parameters using xhr object, you only need to call xhr During open, you can specify parameters for the URL address.
The code is as follows:
<body> <script> var xhr = new XMLHttpRequest() xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1') xhr.send() xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) } } </script> </body>
Query string
Definition of query string: the string (variable) used to send information to the server is added at the end of the URL.
Query string format: speak English? Put it at the end of the URL, and then add the parameter = value. If you want to add multiple parameters, use the & symbol for segmentation. In this form, you can add the data you want to send to the server to the URL.
As shown in the figure:
The nature of parameters carried by GET requests: whether $ ajax() $.get(), or directly use xhr object to initiate GET request. When parameters need to be carried, in essence, parameters are directly appended to the URL address in the form of query string and sent to the server.
As shown in the figure:
The code is as follows:
<body> <script> // $.get(' http://www.liulongbin.top:3006/api/getbooks '{ID: 1, bookname:' journey to the West '}, function (res){ // console.log(res) // }) $.ajax({ method: 'GET', url: 'http://www.liulongbin.top:3006/api/getbooks', data: { id: 1, bookname: 'Journey to the West' }, success: function (res) { console.log(res) } }) </script> </body>
URL encoding and decoding
Definition of URL encoding and decoding: since only English related letters, punctuation marks and numbers are allowed in the URL address, Chinese characters are not allowed in the URL address.
If the URL needs to contain Chinese characters, the Chinese characters must be encoded (escaped).
Principle of URL encoding: use English characters to represent non English characters.
As shown in the figure:
How to encode and decode URL s?
encodeURI() encoded function
As shown in the figure:
Function decodeURL()
The code is as follows:
<body> <script> var str = 'Dark horse programmer' var str2 = encodeURI(str) console.log(str2) console.log('----------') var str3 = decodeURI('%E9%BB%91%E9%A9%AC') console.log(str3) </script> </body>
Use xhr to initiate POST requests
Definition: that is, post submits data to the server.
Steps:
- Create xhr object
- Call XHR Open() function
- Set content type property (fixed writing method)
- Call XHR Send() function, and specify the data to be sent
- Monitor XHR Onreadystatechange event
As shown in the figure:
Data exchange format
Definition of data exchange format: refers to the format of data transmission and exchange between server and client. In the front-end field, the two data exchange formats often mentioned are XML and JSON. JSON is mainly used.
Definition of XML: both XML and HTML are markup languages, but they have nothing to do with each other. (learn the following XML by analogy)
Definition of JSON: JSON is the string representation of js objects and arrays. JSON is essentially a string.
Role of JSON: store and transfer data between computer and network (lightweight text data exchange format).
There are two structures of JSON:
- Object structure
Syntax structure: {key:value,key:value,key:value...}
As shown in the figure: (only the last sentence is written correctly)
- Array structure
Syntax structure: ["java","javascript",30,true...]
As shown in the figure:
Exchange of JSON and JS objects:
- Convert JSON string to JS object - JSON parse()
The following code is shown:
var jsonStr = '{"a": "Hello", "b": "world"}' var obj = JSON.parse(jsonStr) console.log(obj)
- Convert JS object to JSON string - JSON stringify()
The following code is shown:
var obj2 = { a: 'hello', b: 'world', c: false } var str = JSON.stringify(obj2) console.log(str) console.log(typeof str)
Serialization and deserialization:
- Serialization -- converting data objects to string} JSON Stringify() operation
- Deserialization -- converting a string to a data object {JSON Operation of parse() function
New features of XMLHttpRequest Level2
- Set the time limit for HTTP requests
Appearance of time limit: sometimes because Ajax operation is very time-consuming, users will wait a long time if the network speed is slow, so the new timeout attribute can set the time limit of HTTP request.
The code is as follows:
<body> <script> var xhr = new XMLHttpRequest() // Set timeout xhr.timeout = 30 // Set the processing function after timeout xhr.ontimeout = function () { console.log('Request timed out!') } xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks') xhr.send() xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) } } </script> </body>
- Managing form data using FormData objects
Function: it can add data to the form and obtain the value of web form
- Upload file
- Obtain the progress information of data transmission
axios
Definition of Axios: Axios is a library that focuses on network data requests.
Advantages of Axios: Axios is simple and easy to use. Compared with jQuery, Axios is lighter and only focuses on network data requests.
- Axios initiates a GET request
Syntax: Axios Get ('url ', params: {/ * parameter * /}) then(callback)_
As shown in the figure:
- axios initiates a POST request
Syntax: Axios Post ('url ', {/ * parameter * /}) then(callback)_
As shown in the figure:
- Request directly using axios
Directly use axios to initiate GET requests
Send POST requests directly using axios
summary
~ ✨ I finished my study today ✨~
~ENDING~