Ajax- Shallow In and Deep out (2)

1. Summary of Ajax

1.1 introduction of AJAX

  • AJAX is Asynchronous JavaScript And XML
  • AJAX allows you to send asynchronous requests to the server from within the browser, with the biggest advantage: no refresh to retrieve data
  • AJAX is not a new programming language, but a new way to use existing standards together

1.2 introduction of XML

  • XML Extensible Markup Language.
  • XML was designed to transfer and store data, and HTML to present it.
  • XML is similar to HTML, except that HTML has predefined tags, whereas XML has no predefined tags,
  • They’re all custom tags that represent some data.

Let’s say I have student data:

Name = "Sun Wukong"; age = 18 ; Gender = male; <student> <name> <age>18</age> <gender> male </gender> </student>Copy the code

It has now been replaced by JSON.

{"name":" Sun Wukong ","age":18,"gender":" male "}Copy the code

1.3 Features of AJAX

1.3.1 Advantages of AJAX

  1. You can communicate with the server side without refreshing the page
  2. Allows you to update parts of the page based on user events

1.3.2 Disadvantages of AJAX

  1. Cannot rollback without browsing history
  2. Cross-domain problems exist (homologous)
  3. SEO is not friendly

2. HTTP related issues

2.1 MDN document

Request and response notes

2.2 Basic process of HTTP Request Interaction

  1. Sending HTTP requests (request packets) from the browser to the server
  2. After the background server receives the request, the scheduling server processes the request and returns the HTTP response (response message) to the browser.
  3. The browser side receives the response and parses to display the response body/invoke the monitoring callback

2.3 HTTP Request Packets

1. The request

method url GET /product_detail? id=2 POST /loginCopy the code

2. Multiple headers

Host: www.baidu.com Cookie: BAIDUID=AD3B0FA706E; BIDUPSID=AD3B0FA706; Content-type: Application /x-www-form-urlencoded or Application /jsonCopy the code

3. Request body

username=tom&pwd=123
{"username": "tom"."pwd": 123}
Copy the code

2.4 HTTP Response Packets

1. The response status line is status statusText

2. Multiple response headers

Content-Type: text/html; charset=utf-8
Set-Cookie: BD_CK_SAM=1; path=/Copy the code

3. The response body

HTML text/JSON text/JS/CSS/image...Copy the code

2.5 Format of the POST Request Body Parameter

1.Content-Type: application/x-www-form-urlencoded; For example, name=%E5%B0%8F%E6%98%8E&age=12 2. Content-type: application/json; charset= UTF-8 for key-value pairs. Charset = UTF-8 Used for JSON string parameters for example: {“name”: “% e5% B0%8F% e6% 98%8E”, “age”: 12} 3. Content-type: multipart/form-data Used for file upload requests

2.6 Common Response status codes

  • 200 The OK request succeeded. Typically used for GET and POST requests
  • 201 Created Created. The new resource was successfully requested and created
  • 401 Unauthorized/Requests require user authentication
  • 404 Not Found The server failed to find the resource based on the client request
  • 500 Internal Server Error Indicates an Internal Server Error. The request cannot be completed

2.7 Different types of requests and their functions

  • GET: Reads data from the server.
  • POST: Add new data to server (add)
  • PUT: Update the data on the server.
  • DELETE: deletes data on the server.

2.8 Classification of apis

REST APIS: restful (Representational State Transfer layer State transformation)

  1. Sending a request for CRUD operations is determined by the request mode
  2. Multiple operations can be performed on the same request path
  3. The request method uses GET/POST/PUT/DELETE

The REST API: restless

  1. The request mode does not determine the CRUD operation requested
  2. A request path corresponds to only one operation
  3. Usually just GET/POST

2.9 Differences between COMMON HTTP Requests and Ajax Requests

  • An Ajax request is a special type of HTTP request
  • On the server side, there is no difference, the difference is on the browser side
  • Browser-side requests: Only XHR or FETCH makes Ajax requests; all other requests are non-Ajax
  • The browser receives a response

(1) General request: the browser will display the response body data directly, which is often referred to as refresh/jump page. (2) Ajax request: the browser will not do any update to the interface, but just call the monitoring callback function and pass in the response related data

3. Basic use of XHR for native AJAX

3.0 Preparations

3.0.1 Installation node. Js

3.0.2 Install Express (Server side framework)

1. Initialize the environment

npm init --yes
Copy the code

2. Download the Express package

npm install express --save
Copy the code

3. Write JS code

Const express = require('express'); // 2. Const app = express(); // Request encapsulates request packets // Response encapsulates response packets app.get('/', (request, Response) => {// set response.send("Hello Express"); }); Listen (8000, () => {console.log(" Service started, 8000 listening...") ); })Copy the code

4. Run the JS program

node express.js
Copy the code

5. Open the web page and enter informationhttp://127.0.0.1:8000/Display the page

6. Debuggers can view requests and responses

3.0.3 Installing the Node-dev automatic restart tool

If the file content is modified, the service is automatically restarted

node-dev

1. Install

npm i node-dev
Copy the code

2. Start the service

node-dev server.js
Copy the code

3.1 understand

  • You can use the XMLHttpRequest (XHR) object to interact with the server, that is, to send ajax requests
  • The front end can retrieve the data without requiring an entire page refresh.
  • This allows Web pages to update only parts of the page without affecting user actions.

XMLHttpRequest MDN XMLHttpRequest, all AJAX operations are performed through this object

3.2 Steps for using core objects

3.2.1 Creating an XMLHttpRequest Object

var xhr = new XMLHttpRequest();

3.2.2 Setting Request Information (Request Method and URL)

Xhr.open (method, url); // Xhr. setRequestHeader(' content-type ', 'application/x-www-form-urlencoded'); // Xhr. setRequestHeader(' content-type ', 'application/x-www-form-urlencoded');Copy the code

3.2.3 Sending a Request

Xhr.send (body) // Get requests do not pass the body parameter, only post requests

3.2.4 Receiving responses (Event binding, processing the results returned by the server)

//xhr.responseText Receives response data in text format xhr.onreadyStatechange = function () {// Judge If (xhr.status >= 200&& xhr.status < xhr.status >= 200&& xhr.status < 300) {// Process result line header empty line body // response // console.log(xhr.status); // status code // console.log(xhr.statustext); / / state string. / / the console log (XHR. The getAllResponseHeaders ()); // All response headers // console.log(xhr.response); // Response body // Set the text result.innerhtml = xhr.response; } else { } } } }Copy the code

3.3 Use Cases

3.3.1 GET request

Click to return the response information



Create two files, the HTML file used by the browser and the JS file used by the server

Server.js on the server

Const express = require('express'); // 2. Const app = express(); App. get('/server', (request, Response) => {// set response.setHeader(' access-Control-allow-origin ', '*'); // Set response.send("Hello Ajax"); }); // 4. App.listen (8000, () => {console.log(" service started, 8000 port listening... ); })Copy the code

Start the service

node server.js
Copy the code

Front-end page HTML

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, < span style> #result {width: 200px; height: 100px; border: solid 1px #90b; </style> </head> <body> <button> Click send request </button> <div id="result"></div> <script> // get button element const BTN = document.getElementsByTagName('button')[0]; const result = document.getElementById("result"); Btn.onclick = function () {//1. Create object const XHR = new XMLHttpRequest(); / / 2. Initialization setting the request method and url XHR. Open (' GET 'and' http://127.0.0.1:8000/server? a=100&b=200&c=300'); // Send parameters: add? To the url. //3. Send xhr.send(); //4. Event binding processes the result returned by the server // on when.... When // readyState is an attribute in the XHR object, Xhr.onreadystatechange = function () {if (xhr.readyState === 4) { Check the response status code 200 404 403 401 500 // 2XX successful if (xhr.status >= 200&& xhr.status < 300) {// Result Line header empty line body // Response // console.log(xhr.status); // status code // console.log(xhr.statustext); / / state string. / / the console log (XHR. The getAllResponseHeaders ()); // All response headers // console.log(xhr.response); // Response body // Set the text result.innerhtml = xhr.response; } else { } } } } </script> </body> </html>Copy the code

GET Request Sets request parameters

Setting URL Parameters

XHR. Open (' GET 'and' http://127.0.0.1:8000/server? a=100&b=200&c=300');Copy the code

3.3.2 rainfall distribution on 10-12 POST request

Place the mouse over the div, send a POST request, and render the response body inside the div

Add a post server. Js

Add the following code to the previous server.js

app.post('/server'.(request, response) = > {
  // Set the response header to allow cross-domain
  response.setHeader('Access-Control-Allow-Origin'.The '*');
  // Set the response body
  response.send("Hello Ajax POST");
});
// Can receive any type of request
app.all('/server'.(request, response) = > {
    // Set response header Settings to allow cross-domain
    response.setHeader('Access-Control-Allow-Origin'.The '*');
    // Response headers, which can be customized
    response.setHeader('Access-Control-Allow-Headers'.The '*');
    // Set the response body
    response.send('HELLO AJAX POST');
});

Copy the code

post.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, < span style> #result{width:200px; height:100px; border:solid 1px #903; } </style> </head> <body> <div id="result"></div> <script> const result = document.getelementById ("result"); Result. addEventListener("mouseover", function(){//1. Create object const XHR = new XMLHttpRequest(); / / 2. Initialization setting type and URL XHR. Open (' POST ', 'http://127.0.0.1:8000/server'); SetRequestHeader (' content-type ','application/x-www-form-urlencoded'); // Set the request header xhr.setrequesTheader (' content-type ','application/x-www-form-urlencoded'); xhr.setRequestHeader('name','zgc'); / / 3. XHR. Send (" a = = 200 & 100 & b c = 300 '); // xhr.send('a:100&b:200&c:300'); // xhr.send('1233211234567'); Xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status >= 200&&xhr.status < 300){// if(xhr.status >= 200&&xhr.status < 300){ // Process the result result.innerhtml = xhr.response; }}}}); </script> </body> </html>Copy the code

3.3.3 Setting request Header Information

Set the request header after open () and before send (), see the post code above

Xhr.setrequesheader (' content-type ','application/x-www-from-urlencoded'); // Set the request body Content Type xhr.setrequesHeader (' content-type ','application/x-www-from-urlencoded'); Xhr.setrequesheader ('name', 'ZGC ');Copy the code

Set response headers in server.js to allow custom request headers post to all

response.setHeader('Access-Control-Allow-Header'.The '*');
Copy the code

3.4 JSON Data Request

Server.js adds the following code to the previous server.js

app.all('/json-server'.(request, response) = > {
  // Set the response header to allow cross-domain
  response.setHeader('Access-Control-Allow-Origin'.The '*');
  // Set the response header to allow custom headers
  response.setHeader('Access-Control-Allow-Headers'.The '*');
  // Respond to a data
  const data = {
    name: 'atguigu'
  };
  // Perform string conversion on the object
  let str = JSON.stringify(data)
  // Set the response body
  response.send(str);
});
Copy the code

index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>JSON response </title> <style> #result{width:200px; height:100px; border:solid 1px #89b; } </style> </head> <body> <div id="result"></div> <script> const result = document.getElementById('result'); // Bind the keypress event window.onkeyDown = function(){const XHR = new XMLHttpRequest(); Xhr. responseType = 'json'; / / initialize the XHR. Open (' GET 'and' http://127.0.0.1:8000/json-server '); / / XHR. The send (); Xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status >= 200 && xhr.status < 300){// console.log(xhr.response); // result.innerHTML = xhr.response; Parse (xhr.response); // Let data = json.parse (xhr.response); // console.log(data); // result.innerHTML = data.name; // 2. Automatically convert console.log(xhr.response); result.innerHTML = xhr.response.name; } } } } </script> </body> </html>Copy the code

3.5 Request Timeout and Network Exception

server.js

Add the following code to the previous server.js

// Delay response
app.all('/delay'.(request, response) = > {
    // Set response header Settings to allow cross-domain
    response.setHeader('Access-Control-Allow-Origin'.The '*');
    response.setHeader('Access-Control-Allow-Headers'.The '*');
    setTimeout(() = > {
        // Set the response body
        response.send('Delayed response');
    }, 3000)});Copy the code
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, < span style> #result{width:200px; height:100px; border:solid 1px #90b; } </style> </head> <body> <button> click send request </button> <div id="result"></div> <script> const BTN = document.getElementsByTagName('button')[0]; const result = document.querySelector('#result'); btn.addEventListener('click', function(){ const xhr = new XMLHttpRequest(); Xhr. timeout = 2000; Xhr.ontimeout = function(){alert(" network exception, please try again later!!" ); Xhr.onerror = function(){alert(" There seems to be something wrong with your network!" ); } XHR. Open (" GET ", "http://127.0.0.1:8000/delay"); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status< 300){ result.innerHTML = xhr.response; } } } }) </script> </body> </html>Copy the code

3.6 Canceling a Request

// Abort xhr.abort()

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title> cancel the request </title> </head> <body> <button> Click send </button> </button> click cancel </button> <script> // get the element object const btns = document.querySelectorAll('button'); let x = null; btns[0].onclick = function(){ x = new XMLHttpRequest(); X.o. pen (" GET ", "http://127.0.0.1:8000/delay"); x.send(); } // abort btns[1].onclick = function(){ x.abort(); } </script> </body> </html>Copy the code

3.7 Repeated Sending of Requests

Sets the variable to determine whether the request is repeated

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, </title> </head> <body> <button> Click send </button> <script> // get the element object const BTNS = document.querySelectorAll('button'); let x = null; // let isSending = false; BTNS [0].onclick = function () {if (isSending) x.apport (); // If it is sending, cancel the request and create a new request x = new XMLHttpRequest(); // Change the value isSending = true; X.o. pen (" GET ", "http://127.0.0.1:8000/delay"); x.send(); X.onreadystatechange = function () {if (x.readyState === 4) {isSending = false; if (x.status >= 200 && x.status < 300) { console.log(x.response); } } } } </script> </body> </html>Copy the code

3.8 Solving the Internet Explorer Cache Problem

Problem: In some browsers (IE), ajax will only send the first request due to caching mechanisms, and the remaining multiple requests will not be sent to the browser but will load the data directly from the cache. Solution: The browser cache is logged by URL, so we only need to change the URL address to avoid caching problems

server.js

Add the following code to the previous server.js

Get ('/ IE ', (request, response) => {response.setHeader(' access-Control-allow-origin ', 'access-Control-allow-origin ',' access-control-allow-origin ', The '*'); // Set response.send('HELLO ie-25 '); });Copy the code

index.html

Add the timestamp parameter to xhr.open

XHR. Open (" GET ", "http://127.0.0.1:8000/ie? t='+Date.now());

3.9 AJAX Request Status

Xhr. readyState can be used to view the MDN of the current status of the request

  • 0: indicates that the XMLHttpRequest instance has been generated, but the open() method has not been called
  • 1: the send() method has not been called, but setRequestHeader() can still be used to set the HTTP request header
  • 2: indicates that the send() method has been executed and the header message and status code have been received
  • 3: indicates that the body data is being received from the server
  • 4: Indicates that the server receives all data or fails to receive data this time

3.10 API to summarize

  • XMLHttpRequest() : Constructor to create an XHR object
  • Status: indicates the response status code, for example, 200 or 404
  • StatusText: response statusText such as’ ok ‘, ‘not found’
  • ReadyState: read-only attribute 0-1-2-3-4 identifying the request status
  • Onreadystatechange: Bind listeners to readyState changes
  • ResponseType: Specifies the data type of the response. If it is’ JSON ‘, the response will be parsed automatically
  • Response: Response body data. The type depends on the responseType specified
  • Timeout: specifies the timeout period for a request. The default value is 0, indicating that there is no limit
  • Ontimeout: binding timeout listening
  • Onerror: Binding requests network error listening
  • Open () : Initializes a request with: (method, url[, async])
  • Send (data) : sends a request
  • Abort () : Abort request (between issued and returned)
  • GetResponseHeader (name) : Gets the response header value with the specified name
  • GetAllResponseHeaders () : Gets a string of all response headers
  • SetRequestHeader (name, value) : Sets the request header