AJAX
1. Definitions
Ajax, namely asynchronous javaScript and XML, is a web page development technology to create interactive, fast and dynamic web page applications. It can update some web pages without reloading the whole web page.
Ajax can make web pages update asynchronously by exchanging a small amount of data with the server in the background. This means that a part of a web page can be updated without reloading the whole web page.
- Local refresh: some web pages are updated. Common requirements include: pull-down refresh list, pull-up load more lists, and whether the user name is registered
- Asynchrony: Ajax can continue the follow-up operation when the http response has no result, so as to improve the user experience
- AJAX is not the specification of JavaScript. Ajax uses JavaScript to execute asynchronous network requests
- AJAX requests are executed asynchronously, and the response is obtained through the callback function.
- When submitting a Form, you will find that once the user clicks the Submit button, When the Form is submitted (send HTTP request), the browser will refresh the page, and then tell you whether the operation succeeded or failed in the new page. If unfortunately, due to the slow network or other reasons, you will get a 404 page. (because the working principle of the Web: one HTTP request corresponds to one page)
- If you want the user to stay on the current page and send a new HTTP request at the same time, you must send the new request with JavaScript. After receiving the data, you can update the page with JavaScript. In this way, the user feels that he is still on the current page, but the data can be updated continuously.
2. Basic framework of Ajax
Preliminary work - plug-in installation
- Right click the project folder and click to open it in the inheritance terminal
- Enter the command npm init --yes
- Installing express npm i express
- After installing the modified content, the service plug-in npm install -g nodemon can be restarted automatically. After installation, the service startup command is the nodemon server name. Each time the server content is changed, just save it, and nodemon will restart the service automatically
Officially start writing!
- The code is parsed. Don't worry
Native Ajax
1.get and post requests
main points:
- To comment in code
- Ajax sends an http request through the native XMLHttpRequest () object, obtains the data returned by the server, and then processes it. XMLHttpRequest object is the main interface of Ajax and is used for communication between browser and server: var xht = new XMLHttpRequest();
<-- 01- get and post request.html --> <button>Send request</button> <br> <textarea name="" id="result" cols="30" rows="10"></textarea> <script> // Get element var btn = document.querySelector('button'); // Binding event const result = document.getElementById("result"); let xhr = null; // Because you want to respond to get and post requests on the same page, the xhr declaration is left out // Event listening [ get request ] btn.addEventListener("click", function() { // 1. Create object xhr = new XMLHttpRequest(); // 2. Initialization setting request method and url xhr.open('GET', 'http://127.0.0.1:8000/server',true);// true can be saved (the default is asynchronous), and false indicates synchronization // 3. Send xhr.send(); // 4. Bind the result returned by the event processing server // readystate: // 0: not initialized // 1: Indicates that the open method has been called // 2: The send method has been called // 3: The server returns some data // 4: The server returns all data // Change: triggered when a change occurs xhr.onreadystatechange = function() { // As can be seen from the above, 4 returns all results for the server if (xhr.readyState === 4) { // status code: status if (xhr.status >= 200 && xhr.status < 300) { console.log(xhr.status); // Status code console.log(xhr.statusText); // Status code string console.log(xhr.getAllResponseHeaders); // All response headers console.log(xhr.response); // /The response content corresponding to the get request of the server can be seen from the following code: hello get result.innerHTML = xhr.response; } } } }); // Event Listening 2 [post request] result.addEventListener("mouseover", function() { xhr = new XMLHttpRequest(); xhr.open('POST', 'http://127.0.0.1:8000/server'); xhr.send('a=100&b=200&c=300'); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { result.innerHTML = xhr.response; } } } }); </script>
// server.js // 1. Reference express // const { request, response } = require('express'); const express = require('express'); // It can be seen from the above that express has two requests: request and response // 2. Create application object const app = express(); // 3. Create routing rules // Request is the encapsulation of request message // Response is the encapsulation of response message // 01 get request app.get('/server', (request, response) => { // Set the response header. This setting allows cross domain, whether to include the domain name of the request page. If not, the browser will treat it as a failed request and steal XHR Functions in onerror // (? This is used to indicate which protocol + domain name + port number the request comes from. The server decides whether to agree to the request according to this word) response.setHeader('Access-Control-Allow-Origin', '*'); // Set response response.send('hello get'); }); // 02 post request app.post('/server', (request, response) => { // Set the response header. This setting allows cross domain, whether to include the domain name of the request page. If not, the browser will treat it as a failed request and steal XHR Functions in onerror // (? This is used to indicate which protocol + domain name + port number the request comes from. The server decides whether to agree to the request according to this word) response.setHeader('Access-Control-Allow-Origin', '*'); // Set response response.send('hello get'); }); // 4. Listening port start service app.listen(8000, () => { console.log("Server started with port number 8000..."); });
2.JSON
main points:
- Set response data to Js object: XHR responseType = 'json';
- Parse string data into js object: JSON parse()
- Calling properties in object: XHR response. name
<-- 02-JSON.html--> <textarea name="" id="result" cols="30" rows="10"></textarea> <script> const result = document.getElementById("result"); window.onkeydown = function() { const xhr = new XMLHttpRequest(); // Set the type of response body data (you cannot add xhr.responseType = 'json' when using manual data conversion), // Because if you add this sentence, the data you want to convert is a js object, json Parse () parses a string into a json object, and you will report an error if you convert it again; // If it is added, an error of 'Unexpected token o in JSON at position 1' will be reported xhr.responseType = 'json'; xhr.open('GET', 'http://127.0.0.1:8000/jsonserver'); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { // Manual data conversion // let data = JSON.parse(xhr.response); // console.log(xhr.response); // result.innerHTML = data.name; // Automatically convert data result.innerHTML = xhr.response.name; } } } } </script>
// 03-json app.get('/jsonserver', (request, response) => { response.setHeader('Access-Control-Allow-Origin', '*'); // Response header response.setHeader('Access-Control-Allow-Headers', '*'); // Respond to a data const data = { name: 'atkjasdfh' }; // String conversion of objects let str = JSON.stringify(data); // Set response response.send(str); });
3.ie cache problem
- If the chorme browser is used, after the server data is updated, refresh the browser to get the updated data of the server; However, if you use an IE browser, you can't get the updated data from the server because ie uses a strong cache.
The IE browser will cache the get and XHR contents in the web page. In the IE browser, if the request method is get, the IE browser will identify it. If the url of the get request is the first request, it will request the background of the project and obtain data from the database. If the url of the get request is not the first request, the url will not request the background of the project, The IE browser will directly get the data obtained from the last url from the cache. No matter what plug-in's get request, the IE browser will process it in this way
- One way to solve this problem is to add a timestamp to the URL of the request as a parameter. When the Ie browser receives the URL, it will regard it as the URL of the first request because the timestamp in the parameter is different.
<-- 03-ie Cache problem.html --> <button>Button</button> <br> <textarea name="" id="result" cols="30" rows="10"></textarea> <script> const btn = document.querySelector("button"); let result = document.getElementById("result"); btn.addEventListener("click", function() { const xhr = new XMLHttpRequest(); // url adds a timestamp as a parameter xhr.open('GET', 'http://127.0.0.1:8000/ie?t=' + Date.now()); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status == 200) { result.innerHTML = xhr.response; } } } }); </script>
// 03 ie cache problem app.get('/ie', (request, response) => { // Set the response header. This setting allows cross domain response.setHeader('Access-Control-Allow-Origin', '*'); // Set the response. When you change here, refresh the page and the response content received by the page will change accordingly response.send('hello get-4'); });
04. Network exception and timeout
Manufacturing browser network exception: press f12 - Network - select Offline
main points:
- Timeout: XHR timeout
- Timeout callback function: XHR ontimeout
- Network exception callback function: XHR onerror
- Callback time of the server setTimeout() (how long will it respond)
<-- 04-Network exception and timeout retransmission.html--> <button>Button</button> <br> <textarea name="" id="result" cols="30" rows="10"></textarea> <script> const btn = document.querySelector("button"); let result = document.getElementById("result"); btn.addEventListener("click", function() { const xhr = new XMLHttpRequest(); // Set timeout 2s xhr.timeout = 2000; // Set timeout callback function xhr.ontimeout = function() { alert('Network exception, please try again later!!'); } // Set callback function of network exception xhr.onerror = function() { alert("There seems to be something wrong with your network!!"); } xhr.open('GET', 'http://127.0.0.1:8000/web'); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status == 200) { result.innerHTML = xhr.response; } } } }); </script>
// 04 -- Network exception or timeout app.get('/web', (request, response) => { // Set the response header. This setting allows cross domain response.setHeader('Access-Control-Allow-Origin', '*'); response.setHeader('Access-Control-Allow-Headers', '*'); // Set the response to respond 3 seconds after receiving the request setTimeout(() => { response.send('Deferred Response '); }, 3000) });
05. Cancellation request
main points:
- Interrupt request: XHR abort();
<-- 05.Cancel request.html --> <button>Send request</button> <button>Cancel request</button> <script> var btn = document.querySelectorAll("button"); let xhr = null; // Send request btn[0].onclick = function() { xhr = new XMLHttpRequest(); xhr.open("GET", "http://127.0.0.1:8000/delay"); xhr.send(); } // Interrupt request btn[1].onclick = function() { // abort interrupt xhr.abort(); } </script>
// 05 -- cancel request app.get('/delay', (request, response) => { response.setHeader('Access-Control-Allow-Origin', '*'); response.setHeader('Access-Control-Headers', '*'); // Set response setTimeout(() => { response.send('Sent successfully'); }, 3000) })
6. Repeated requests
main points:
- The flag isSending used to determine whether an ajax request is being sent
- Interrupt new request XHR abort();
<button>Send request</button> <script> var btn = document.querySelectorAll("button"); let xhr = null; // Create a flag to judge whether the request is being sent. If it is being sent, stop calling duplicate requests let isSending = false; // Send request btn[0].onclick = function() { // When entering a new request, first determine whether an ajax request is being sent if (isSending) xhr.abort(); xhr = new XMLHttpRequest(); // Click in to indicate that the request has been sent to the service, and isSending is changed to true isSending = true; xhr.open("GET", "http://127.0.0.1:8000/delay"); xhr.send(); xhr.onreadystatechang = function() { if (xhr.readyState === 4) { isSending = false; } } } </script>