Ajax_3 Ajax principle
01-Ajax principle-XMLHttpRequest
Using XMLHttpRequest
step:
- Create an XMLHttpRequest object
- Configure the request method request url URL
- Listen to the loadend event and accept the response result
- make a request
Requirement: Communicate with the server using the XMLHttpRequest object
Code example
// 1. Create an XMLHttpRequest object const xhr = new XMLHttpRequest() // 2. Configure the request method and request url address xhr.open('GET', 'http://hmajax.itheima.net/api/province') // 3. Listen to the loadend event and receive the response result xhr. addEventListener('loadend', () => {<!-- --> console. log(xhr. response) // string to object const data = JSON. parse(xhr. response) console. log(data. list) // array to string console.log(data.list.join('<br>')) // insert into the page document.querySelector('.my-p').innerHTML = data.list.join('<br>') }) // 4. Initiate a request xhr. send() </script>
02-XMLHttpRequest-query parameters
Definition: The browser provides additional information to the server, allowing the server to return the results the browser wants.
Syntax:
- ?Parameter name 1 = value 1 & amp; parameter name 2 = value 2 (after the question mark, multiple values are connected with & amp;)
The parameter name is set in the interface document!
Requirement: Use XHR to carry query parameters to display a list of cities under a certain province
Code example
<script> // 1. Create an xhr instance object const xhr = new XMLHttpRequest() // 2. Initiate a request xhr.open('GET', 'http://hmajax.itheima.net/api/city?pname=Jiangxi Province') xhr. addEventListener('loadend', () => {<!-- --> console. log(xhr. response) // object to string const data = JSON. parse(xhr. response) console. log(data) // array to string, separated by newlines console.log(data.list.join('<br>')) // Insert rendering document.querySelector('.city-p').innerHTML = data.list.join('<br>') }) xhr. send() </script>
03-Region query
Requirement: According to the name of the province and city, query the list of corresponding regions
Code example
<script> // register click event document.querySelector('.sel-btn').addEventListener('click', () => {<!-- --> // 2. Collect province and city names const pname = document.querySelector('.province').value const cname = document.querySelector('.city').value // 3. Organize the string of query parameters const qObj = {<!-- --> pname, cname } // convert query parameter object -> query parameter string const paramsObj = new URLSearchParams(qObj) // Use the toString() method to convert the instance object to a string const queryString = paramsObj.toString() console. log(queryString) // 1. Create an xhr instance object const xhr = new XMLHttpRequest() // 2. Send a request to the server xhr.open('GET', `http://hmajax.itheima.net/api/area?${<!-- -->queryString}`) // 3. The listening function listens to the server response information xhr. addEventListener('loadend', () => {<!-- --> console. log(xhr. response) // Convert the returned result object to a string const data = JSON. parse(xhr. response) console. log(data. list) // Map the data in the array to the label through the map array, remember to convert the array into a large string const htmlStr = data.list.map(item => {<!-- --> return `<li class="list-group-item">${<!-- -->item}</li>` }).join('') console. log(htmlStr) document.querySelector('.list-group').innerHTML = htmlStr }) // 4. Send request xhr. send() }) </script>
04-XMLHttpRequest-submit data
Requirements: Submit username and password through XHR to complete the registration function
Code example
document.querySelector('.reg-btn').addEventListener('click', () => {<!-- --> const xhr = new XMLHttpRequest() xhr.open('POST', 'http://hmajax.itheima.net/api/register') xhr. addEventListener('loadend', () => {<!-- --> console. log(xhr. response) }) // Configure the request parameters yourself xhr.setRequestHeader('Content-Type', 'application/json') // ready to submit data const userObj = {<!-- --> username: 'liubuzhu', password: '7654321' } //Convert the parameter object to a string request body const userStr = JSON. stringify(userObj) // Set the request body: make a request xhr. send(userStr) }) </script>Whether it is a request or a query, you need to configure the object yourself to operate after conversion through the API
Query parameters use the path to pass parameters after?.
After submitting the request parameters, configure the request object by yourself, in xhr.send (request parameters)
05-Know Promise
Definition: The promise object is used to represent the final completion (or failure and result) of an asynchronous operation
Benefits of promise
- clearer logic
- Understand the inner workings of axios functions
- Can solve the callback function below the problem
Syntax:
- Create a promise object, pass resolve and reject parameters
- Execute the asynchronous task and pass the result, successfully passed to resolve, failed to pass to reject
- Accept the result: success then method, failure catch method
Code example
<script> const p = new Promise((resolve,reject) => {<!-- --> // 2. Execute asynchronous code setTimeout(() => {<!-- --> // If successful, directly pass the actual parameters to resolve resolve('Simulate the successful result of Ajax request') // If it fails, pass the actual parameter directly to reject reject('Simulate Ajax request failure result') },2000) }) // 3. Get the result p.then(result => {<!-- --> console. log(result) }).catch(error => {<!-- --> console. log(error) }) </script>
- Note the use of the second step.
06-Three states of the Promise object
Function
- Understand how Promise objects are associated with handler functions, and the order in which code is executed.
- pending state (pending) new Promise() : initial state, neither fulfilled nor rejected
- fulfilled state (fulfilled) .then (callback function): means, the operation completed successfully
- rejected status (rejected) .catch(callback function): means, the operation failed
- Note: Once a Promise object is fulfilled or rejected, it has been finalized and its state cannot be changed.
Code example
<script> // When the Promise object is created (pending state), the code here will be executed console.log('Promise object starts execution') // 2. Execute asynchronous code, wait for the execution result to return to the actual parameter, and then cash out or reject the result setTimeout(() => {<!-- --> // After resolve is called, the fulfilled state - fulfilled then() resolve('Simulate AJAX request - success result') // After reject is called, rejected status - rejected catch() reject(new Error('Simulate AJAX request - failure result')) }, 2000) </script>To understand the execution timing of the three states, first execute the synchronous statement in the Promise, then call the two states of fulfillment and rejection, and wait until the asynchronous code is executed and the results are returned to the two states.
07-Use Promise + XHR to get the list of provinces
step:
* 1. Create a Promise object
* 2. Execute the XHR asynchronous code to get the list of provinces
* 3. Associate the success or failure function for subsequent processing
Code example
<script> // 1. Create a Promise object const p = new Promise((resolve,reject) => {<!-- --> // 2. Execute the XHR asynchronous code to get the list of provinces const xhr = new XMLHttpRequest() xhr.open('GET', 'http://hmajax.itheima.net/api/province') xhr.addEventListener('loadend',() => {<!-- --> // Check the response status code // console. log(xhr. status) if (xhr.status >= 200 & amp; & amp; xhr.status < 300) {<!-- --> resolve(JSON.parse(xhr.response)) //string to object } else {<!-- --> // Error We need to create an error instance object and pass the error message to the constructor. When the implementation is passed to the swap function reject(new Error(xhr. response)) } }) xhr. send() }) // 3. Associate the success or failure function for subsequent processing p.then(result => {<!-- --> document.querySelector('.my-p').innerHTML = result.list.join('<br>') }).catch(error => {<!-- --> // The error message returned by the server is returned to the page document.querySelector('.my-p').innerHTML = error.message }) </script>
08-Encapsulate simple axios-query, request, submit
Requirement: Based on Promise + XHR, encapsulate the myAxios function to obtain the list of provinces.
- Goal: Encapsulation_simple axios function_get list of provinces
1. Define the myAxios function, receive the configuration object, and return the Promise object
* 2. Initiate an XHR request, the default request method is GET
* 3. Call success/failure handler
* 4. Use the myAxios function to get the list of provinces to display
Code example
function myAxios(config) {<!-- --> return new Promise((resolve, reject) => {<!-- --> const xhr = new XMLHttpRequest() if (config.params) {<!-- --> const paramsObj = new URLSearchParams(config.params) const queryString = paramsObj.toString() config.url + = `?${<!-- -->queryString}` } xhr.open(config.method || 'GET', config.url) xhr. addEventListener('loadend', () => {<!-- --> if (xhr.status >= 200 & amp; & amp; xhr.status < 300) {<!-- --> resolve(JSON. parse(xhr. response)) } else {<!-- --> reject(new Error(xhr. response)) } }) if (config.data) {<!-- --> const jsonStr = JSON. stringify(config. data) xhr.setRequestHeader('Content-Type', 'application/json') xhr. send(jsonStr) } else {<!-- --> xhr. send() } }) } //Call the function directly below (just use the same as axios() first) to configure according to actual needs myAxios({<!-- --> url: 'http://hmajax.itheima.net/api/register', method: 'POST', data: {<!-- --> usename: 'myaxios010', password: '99999999' } }).then(result => {<!-- --> console. log(result) }).catch(error => {<!-- --> console.dir(error) }) })
August 7, 2023 15:38:27
There will be a comprehensive case, a separate issue will be published, and it will be completed at the same time.