This is the fourth day of my participation in the August Text Challenge.More challenges in August

Today we are going to learn about Ajax, which is a way of making network requests from the front and back end. You can make requests to the server without a page refresh to get some information

1. Summary of Ajax

1.1 introduction of AJAX

Asynchronous JavaScript And XML can be used to send Asynchronous requests from the browser to the server. Fetching data without refreshing 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 is designed to transfer and store data. XML is similar to HTML, except that HTML has predefined tags. XML has no predefined tags, but all custom tags, which represent some data.

For example, I have a student data: name = “Sun Wukong”; age = 18 ; Gender = “male”; Expressed in XML:

<student>
	<name>The Monkey King</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

Developer.mozilla.org/zh-CN/docs/…

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 /login

2. Multiple headers

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

3. Request body

username=tom&pwd=123 {"username": "tom", "pwd": 123}

2.4 HTTP Response Packets

  1. Response status line:status statusText
  2. Multiple response headers

Content-Type: text/html; charset=utf-8 Set-Cookie: BD_CK_SAM=1; Path =/ 3. Response body HTML text/JSON text /js/ CSS/image…

2.5 Format of the POST Request Body Parameter

  1. Content-Type: application/x-www-form-urlencoded; charset=utf-8

Name =%E5%B0%8F%E6%98%8E&age=12 2. Content-type: application/json; 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. Generally used for GET and POST requests 201 Created Created. 401 Unauthorized/Requests require user authentication 404 Not Found The Server could Not find the resource based on the client request. 500 Internal Server Error The Server failed to complete the request

2.7 Different types of requests and their functions

  1. GET: From the serverreadData (search)
  2. POST: To the serveraddNew data (plus)
  3. PUT: updateServer side already data (change)
  4. DELETE: deleteServer-side data (Delete)

2.8 Classification of apis

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

(1) The CRUD operation is determined by the request mode. (2) Multiple operations can be performed on the same request path. (3) The request mode uses GET, POST, PUT, and DELETE. Non-rest apis: Restless (1) Request methods do not determine the CRUD operations requested (2) A request path corresponds to only one operation (3) Generally only GET/POST

2.9 Differences between COMMON HTTP Requests and Ajax Requests

  1. An Ajax request is a special type of HTTP request
  2. On the server side, there is no difference, the difference is on the browser side
  3. Requests sent by the browser: OnlyXHRfetchAjax requests are made, and everything else is non-Ajax
  4. 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

nodejs.cn/

3.0.2 Installing the Express (Server Framework)

www.expressjs.com.cn/

  1. Initializing the Environment
npm init --yes
Copy the code
  1. Download the express package
npm install express --save
Copy the code
  1. Write JS code
// 1. Introduce express
const express = require('express');

// 2. Create application objects
const app = express();

// 3. Create routing rules
// Request encapsulates request packets
// Response encapsulates the response packet
app.get('/'.(request, response) = > {
  // Set the response
  response.send("Hello Express");
});

// 4. Listen on the port and start the service
app.listen(8000.() = > {
  console.log("Service started, listening on port 8000...");
 })
Copy the code
  1. Running a JS program
Node.\ 01Express uses.jsCopy the code

  1. The page is displayed

  1. The debugger can view requests and responses

3.0.3 Installing the Nodemon Automatic Restart Tool

If the file content is modified, the service is automatically restartedwww.npmjs.com/package/nod… The installation

npm install -g nodemon
Copy the code

Start the service

ndoemon server.js
Copy the code

3.1 understand

  1. useXMLHttpRequest(XHR) objects can interact with the server, that is, send Ajax requests
  2. The front end can retrieve the data without requiring an entire page refresh.
  3. This allows Web pages to update only parts of the page without affecting user actions.

Developer.mozilla.org/zh-CN/docs/… XMLHttpRequest, all AJAX operations are done through this object

3.2 Steps for using core objects

3.2.1 Creating an XMLHttpRequest Object

var xhr = new XMLHttpRequest();
Copy the code

3.2.2 Setting Request Information (Request Method and URL)

// Request mode
xhr.open(method, url);
// The request header can be set
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 argument, only post requests
Copy the code

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

// xhr.responsexml receives response data in XML format
//xhr.responseText receives response data in text format
xhr.onreadystatechange = function (){
	// readyState is an attribute in the XHR object that represents states 0, 1, 2, 3, 4
	if(xhr.readyState == 4 && xhr.status == 200) {var text = xhr.responseText;
		console.log(text); }}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

// 1. Introduce express
const express = require('express');

// 2. Create application objects
const app = express();

// 3. Create routing rules
app.get('/server'.(request, response) = > {
  // Set response header Settings to allow cross-domain
  response.setHeader('Access-Control-Allow-Origin'.The '*');
  // Set the response body
  response.send("Hello Ajax");
});

// 4
app.listen(8000.() = > {
  console.log("Service started, listening on port 8000...");
 })
Copy the code

Start the service

node server.js
Copy the code

Front-end page HTML

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Ajax GET request</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: solid 1px #90b;
    }
  </style>
</head>
<body>
  <button>Click Send request</button>
  <div id="result"></div>
  <script>
    // Get the button element
    const btn = document.getElementsByTagName('button') [0];
    const result = document.getElementById('result');
    // Bind events
    btn.onclick = function(){
      // 1. Create objects
      const xhr = new XMLHttpRequest();
      // 2. Initialize the request method and URL
      xhr.open('GET'.'http://127.0.0.1:8000/server')
      / / 3. Send
      xhr.send();
      // 4. The event binding processes the result returned by the server
      xhr.onreadystatechange = function(){
        // readyState is an attribute in the XHR object that represents states 0, 1, 2, 3, 4
        // Check (server returns all results)
        if(xhr.readyState === 4) {// Check the response status code 200 404 403 401 500
          if(xhr.status >= 200 && xhr.status < 300) {// Process the result line header with an empty line body
            / / response
            console.log('Status code', xhr.status); / / status code
            console.log('Status string', xhr.statusText); // Status string
            console.log('All response headers', xhr.getAllResponseHeaders()); // All response headers
            console.log('Response body', xhr.response); / / response body
            
            // Set the text of result
            result.innerHTML=xhr.response;
          }else{}}}}</script>
</body>
</html>
Copy the code

Set request parameters

Setting URL Parameters

xhr.open('GET'.'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

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");
});

Copy the code

post.html

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>The Ajax POST request</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: solid 1px # 903;
    }
  </style>
</head>
<body>
  <div id="result"></div>
  <script>
    // Get the element object
    const result = document.getElementById('result');
    // Bind events
    result.addEventListener("mouseover".function(){
      // 1. Create objects
      const xhr = new XMLHttpRequest();
      // 2. Initialize the type (request mode) and URL
      xhr.open('POST'.'http://127.0.0.1:8000/server');
      // 3. Send set request parameters (request body)
      xhr.send('a=100&b=200&c=300');
      // 4. Event binding
      xhr.onreadystatechange = function(){
        / / determine
        if(xhr.readyState === 4) {if(xhr.status >=200 && xhr.status < 300) {// Process the result returned by the serverresult.innerHTML = xhr.response; }}}});</script>
</body>
</html>
Copy the code

Set the request header

// Set the type of the request body content
xhr.setRequesHeader('Content-Type'.'application/x-www-from-urlencoded');
// Customize header information
xhr.setRequesHeader('name'.'ykyk');
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

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
<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>JSON</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 keyboard press event
    window.onkeydown = function(){
      // Send the request
      const xhr = new XMLHttpRequest();
      // *2*.(automatic conversion) Set the type of the response body data (automatic conversion)
      xhr.responseType = 'json';
      / / initialization
      xhr.open('GET'.'http://127.0.0.1:8000/json-server');
      / / send
      xhr.send();
      // Event binding
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4) {if(xhr.status >= 200 && xhr.status < 300) {console.log(xhr.response);
            // 1. Convert data manually (string to JSON)
            // let data = JSON.parse(xhr.response); // Convert to JSON
            // result.innerHTML = data.name;
            // *2*. (automatic conversion)
            result.innerHTML = xhr.response.name; // Automatically changed to JSON}}}}</script>
</body>
</html>
Copy the code

3.5 Request Timeout and Network Exception

// Set timeout (2 seconds)
xhr.timeout = 2000;
// Timeout callback
xhr.ontimeout = function(){
	alert('Network timed out, please try again later')}// Network exception callback
xhr.onerror = function(){
	alert('Network exception, please try again later')}Copy the code

3.6 Canceling a Request

// Manually cancel
xhr.abort()
Copy the code

3.7 Repeated Sending of Requests

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

xhr.open("get"."/testAJAX? t="+Date.now());
Copy the code

3.9 AJAX Request Status

xhr.readyStateCan be used to view the current status of the requestDeveloper.mozilla.org/zh-CN/docs/…

  • 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(): creates the XHR object’s constructor
  • status: Indicates the response status code, for example, 200 or 404
  • statusText: Response status text such as’ OK ‘, ‘not found’
  • readyState: read-only attribute 0-1-2-3-4 identifies the request status
  • onreadystatechange: Binds listeners to readyState changes
  • responseType: Specifies the response data type. If it is’ JSON ‘, the response will be parsed automatically
  • responseResponseType: Response body data, type depending on responseType specified
  • timeout: Specifies the request timeout period. The default value is 0, indicating that there is no limit
  • ontimeout: Binds timeout listeners
  • onerror: Binding requests network error listening
  • open()Initializes a request with the following parameters:(method, url[, async])
  • send(data): Send a request
  • abort(): Interrupt request (sent to return)
  • 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

4. AJAX in jQuery

4.1 get request

$.get(url, [data], [callback], [type])
Copy the code
  • Url: Indicates the requested URL
  • Data: parameter carried in the request
  • Callback: callback function when loading successfully
  • Type: Sets the returned content format, XML, HTML, script, JSON, text, _default

4.2 a post request

$.post(url, [data], [callback], [type])
Copy the code
  • Url: Indicates the requested URL
  • Data: parameter carried in the request
  • Callback: callback function when loading successfully
  • Type: Sets the returned content format, XML, HTML, script, JSON, text, _default

4.3 General Methods

$.ajax({
	// url
	url: 'http://127.0.0.1:8000/jquery-server'./ / parameters
	data: {a:100.b:200},
	// Request type
	type: 'GET'.// Response body result
	dataType: 'json'.// Successful callback
	success: function(data){console.log(data); },// The timeout period
	timeout: 2000.// Failed callback
	error: function(){console.log('Error pulling ~'); },/ / headers
	headers: {
		c: 300.d: 400}})Copy the code

5. Cross domain

5.1 Same Origin Policy

  • The same-Origin Policy, first proposed by Netscape, is a security Policy for browsers
  • Same-origin: The protocol, domain name, and port number must be the same
  • Cross domain: Violating the same origin policy is cross domain

5.2 How can I Resolve the Cross-Domain Problem

5.2.1 the json

1) What is JSONP

JSONP(JSON with Padding) is an unofficial cross-domain solution, developed purely through the ingenuity of programmers, that supports only GET requests.

2) How does JSONP work?

Some tags on web pages naturally have cross-domain capabilities, such as the IMG link Iframe script. JSONP takes advantage of the cross-domain capabilities of script tags to send requests.

3) Use of JSONP

1. Dynamically create a script tag
var script = document.createElement("script");
Copy the code
2. Set the SRC of script and set the callback function
script.src = "http://localhost:3000/testAJAX? callback=abc";
function abc(data) {
	alert(data.name);
};
Copy the code
3. Add script to body
document.body.appendChild(script);
Copy the code
4. Route processing on the server
router.get("/testAJAX" , function (req , res) {
	console.log("Request received");
	var callback = req.query.callback;
	var obj = {
		name:"Sun Wukong".age:18
	}
	res.send(callback+"("+JSON.stringify(obj)+")");
});
Copy the code

4) JSONP in jQuery

<! DOCTYPEhtml>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
	</head>
	<body>
		<button id="btn">button</button>
		<ul id="list"></ul>
		<script type="text/javascript" src=". / jquery - 1.12.3. Js. ""></script>
		<script type="text/javascript">
			window.onload = function () {
				var btn = document.getElementById('btn')
				btn.onclick = function () {
					$.getJSON("http://api.douban.com/v2/movie/in_theaters?callback=?".function(data) {
						console.log(data);
						// Get all entries for movies
						var subjects = data.subjects;
						// Iterate over the movie entry
						for(var i=0 ; i<subjects.length ; i++){
							$("#list").append("<li>"+
							subjects[i].title+"<br />"+
							"<img src=\""+subjects[i].images.large+"\" >"+
							"</li>"); }}); }}</script>
</body>
</html>
Copy the code

5.2.2 CORS

Developer.mozilla.org/zh-CN/docs/…

1) What is CORS?

Cross-origin Resource Sharing (CORS) : Cross-domain Resource Sharing. CORS is the official cross-domain solution, which does not need to do any special operations in the client side. It is completely processed in the server, supporting GET and POST requests. Cross-domain resource sharing standards have added a new set of HTTP header fields that allow servers to declare which sources have access to which resources through browsers

2) How does CORS work?

CORS sets a response header to tell the browser that the request is cross-domain and the browser will allow the response after receiving it.

3) Use of CORS

Mainly server-side Settings:

router.get("/testAJAX" , function (req , res) {
	// Response headers are set with res to allow cross-domain requests
	/ / res. Set (" Access - Control - Allow - Origin ", "http://127.0.0.1:3000");
	res.set("Access-Control-Allow-Origin"."*");
	res.send("Response returned by testAJAX");
});
Copy the code