web123456

AJAX (1): Native AJAX, HTTP protocol, Ajax environment configuration, AJAX send a request, AJAX requests in the problem

I. OriginalAJAX

1. What is ajax

AJAX is Asynchronous throughout.Javascript And XML, asynchronous js and XML

AJAX allows you to send the server in the browser theasynchronous request, the biggest advantage:Fetch data without refreshingAJAX is not a new programming language, but a new way of using existing standards together.

multilingualism

Extensible Markup Language (XML) XML is designed to transmit and store data. XML is similar to HTML, except that HTML is full of predefined tags, whereas XML has no predefined tags, but all customized tags, which are used to represent some data. (Currently replaced by JSON)

Features.

Pros:
(1) You can communicate with the server side without refreshing the page.
(2) allows you to update part of the page content based on user events (mouse events, document events).
Drawbacks:
(1) There is no browsing history and you cannot go back.
(2) There are cross-domain issues (homologation)
(3) SEO unfriendly (can't find it in the view source code)

II. HTTP Protocol

HTTP is known as hypertext transport protocol, which specifies the rules for communication between browsers and World Wide Web servers. It specifies the request and response formats and parameters

Request Message:Request Headers

classifier for objects in rows such as words:Request type(get,post) / url type() / HTTP protocol version /

beginning or end:Host:Value Cookie: Value Content-type:value User-Agent:Value

blank line:: Fixed

style: null if GET request body, can be left empty if POST

Response Headers:Response Headers

Lines: HTTP Protocol Version(1.1) / Response Status(200) / Response Status String(ok)

Header.Content-type:value Content-length:value Content-encoding:valuewait a minute!

blank line:

BODY.HTML syntax content

AJAX environment configuration

1. Download and install the configuration environment

download and installnode.js needs to be installed, just type in vscode => terminal => current directory => type innpm i express;

Then introduce express, the

  1. // 1. Introducing express
  2. const express = require('express');
  3. // 2. Creating Application Objects
  4. const app = express();
  5. // 3. Creating Routing Rules
  6. //request encapsulates the request message
  7. //response encapsulates the response message
  8. app.get('/', (request, response) => {
  9. //Setting the response
  10. response.send('HELLO EXPRESS')
  11. });
  12. //4. Listening on the port to start the service
  13. (8000, () => {
  14. ('Service started, listening on port 8000 。。。。。');
  15. })

  

Then you can see the response message by typing :127.0.0.1:8000 in your browser 

When there is a port occupied error: address already in use :::8000 or the following node, you can use ctrl+c to release the port.

AJAX send a request

1. Preparation for sending requests

  1. <head>
  2. <meta charset="UTF-8">
  3. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  4. <title>Document</title>
  5. <style>
  6. .box {
  7. width: 200px;
  8. height: 100px;
  9. border: 1px solid #60cc;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <button>dispatch</button>
  15. <div class="box"></div>
  16. </body>
  1. // 1. Introducing express
  2. const { response } = require('express')
  3. const express = require('express')
  4. // 2. Creating Application Objects
  5. const app = express()
  6. // 3. Creating Routing Rules
  7. app.get('/server', (request, response) => {
  8. //Setting the response header Setting to allow cross-domain
  9. ('Access-Control-Allow-Origin', '*');
  10. //Setting the response body
  11. response.send('HELLO AJAX')
  12. })
  13. // 4. Listening on the port to start the service
  14. (8000, () => {
  15. ('Service started, listening on port 8000 。。。。。');
  16. })

Send a Get request

  1. <style>
  2. .box {
  3. width: 200px;
  4. height: 100px;
  5. border: 1px solid #60cc;
  6. }
  7. </style>
  1. <button>dispatch</button>
  2. <div class="box"></div>

server.js

  1. // 1. Introducing express
  2. const express = require('express')
  3. // 2. Creating Application Objects
  4. const app = express()
  5. // 3. Creating Routing Rules
  6. app.get('/server', (request, response) => {
  7. //Setting the response header Setting to allow cross-domain
  8. ('Access-Control-Allow-Origin', '*');
  9. //Setting the response body
  10. response.send('HELLO AJAX')
  11. })
  12. // 4. Listening on the port to start the service
  13. (8000, () => {
  14. ('Service started, listening on port 8000 。。。。。');
  15. })

Click Send to add the response body to the text box to get the text

onreadystatechange: on when... When; readystate is a property in the xhr object that indicates the state 0 1 2 3 4

change

where 0 is uninitialized; 1 is the end of the open call; 2: the end of the send call 3: the server returns part of the results 4: the server returns all the results

  1. <script>
  2. // Get button element\
  3. const btn = ('button')[0]
  4. const result = ('.box')
  5. //bind an event
  6. = function () {
  7. // 1. Creating Objects
  8. const xhr = new XMLHttpRequest()
  9. //2Initialization Setting the request request method and url
  10. xhr.open('GET', 'http://127.0.0.1:8000/server')
  11. // 3. . send .
  12. xhr.send();
  13. // 4. Event binding to handle the results returned by the server side
  14. //onWhen... When; readystate is a property in the xh object that indicates the state0 1 2 3 4 change
  15. // included among these0 - uninitialized1 - openend of call2 - sendend of call3 - The server returns partial results4 - The server returns all results
  16. = function () {
  17. // Judgment (assuming the server returns all results)
  18. if ( === 4)
  19. // Determine response status200 404 403 500
  20. // 2The response statuses beginning with203 201
  21. if (xhr.status >= 200 && xhr.status < 300) {
  22. //Processing result Header Empty line Body
  23. // 1. Response line
  24. /* (xhr.status);//status code
  25. ();//Status String
  26. (());//All response headers
  27. ();//response body*/
  28. // Setting the text in the box
  29. =
  30. }
  31. }
  32. }
  33. </script>

get passes a parameter: in the url suffix parameter, use theSeparation, = assignment, e.g. ?a=100&b=200&c=300

Send a post request

  1.  <style>
  2.         .result {
  3.             width: 200px;
  4.             height: 100px;
  5.             border: 1px solid red;
  6.         }
  7.     </style>
  8. </head>
  9. <body>
  10.     <div class="result"></div>

First get the box and add mouseover events to it

Then create the XMLHttpRequest object; and initialize it to set the request method and the url

By setting the request header

and then send the request.Post passes parameters into send().

Then it is event-bound onreadystetechange to process the results returned by the server;

First determine whether it is equal to 4, i.e., the server has returned all the resultant states, the

If it is equal to 4, then in determining whether the response status is 200, that is, the correct response

After adding the response to the box via innerHTML

  1. <script>
  2. const result = ('.result')
  3. ('mouseover', function () {
  4. // 1. Creating Objects
  5. const xhr = new XMLHttpRequest()
  6. //2. Initialize, set request type and url
  7. xhr.open('POST', 'http://127.0.0.1:8000/server');
  8. // Set the request header Content-Type sets the request body type, you can also define your own but it will report an error.
  9. // application/x-www-form-urlencoded parameter query string fixed writing style
  10. ('Content-Type', 'application/x-www-form-urlencoded')
  11. // 3. . send .
  12. //Post request setup parameters
  13. xhr.send('a=100&b=200&c=300');
  14. // 4. Event Binding Handling results returned by the server
  15. = function () {
  16. if ( === 4) {
  17. if (xhr.status >= 200 && xhr.status < 300) {
  18. =
  19. }
  20. }
  21. }
  22. })
  23. </script>

Then add the post routing rule within

  1. // 1. Introducing express
  2. const express = require('express')
  3. // 2. Creating Application Objects
  4. const app = express()
  5. // 3. CreategetRouting Rules
  6. app.get('/server', (request, response) => {
  7. //Setting the response header Setting to allow cross-domain
  8. ('Access-Control-Allow-Origin', '*');
  9. //Setting the response body
  10. response.send('HELLO AJAX')
  11. })
  12. // 3. Creating post routing rulesallCan accept any type of request
  13. app.all('/server', (request, response) => {
  14. //Setting the response header Setting to allow cross-domain
  15. ('Access-Control-Allow-Origin', '*');
  16. // Setting the response header
  17. ('Access-Control-Allow-Headers', '*');
  18. //Setting the response body
  19. response.send('HELLO AJAX POST')
  20. })
  21. // 4. Listening on the port to start the service
  22. (8000, () => {
  23. ('Service started, listening on port 8000 。。。。。');
  24. })

Response to send object data

When responding to an object data, you need to perform a string conversion of the object data by () and then add the converted string to the response body

  1. app.all('/json-server', (request, response) => {
  2. //Setting the response header Setting to allow cross-domain
  3. ('Access-Control-Allow-Origin', '*');
  4. // Setting the response header
  5. ('Access-Control-Allow-Headers', '*');
  6. // Responding to a data
  7. const data = {
  8. name: 'lalala'
  9. };
  10. // String conversion of object data
  11. let str = (data)
  12. //Setting the response body
  13. response.send(str)
  14. }

When the server conversion result is a string, the page can not be recognized, so this time you need to convert the json string to a js object; there are the following methods:

(1) Manual transformation of data

  1. let data = JSON.parse(xhr.response)
  2. = data.name

(2) By automatic conversion

Setting the response body data type

  = 'json'
  1. console.log(xhr.response);
  2. = xhr.response.name

V. AJAX issues

Caching issues

  1. app.get('/ie', (request, response) => {
  2. //Setting the response header Setting to allow cross-domain
  3. ('Access-Control-Allow-Origin', '*');
  4. //Setting the response body
  5. response.send('HELLO IE-3')
  6. })

When you change the response body, IE will not be updated, but go to the cache, or the last response body; the solution is to add a timestamp after the url, so that each time the url is not the same, so that there will be no change in the response body when IE go to the cache does not update the problem

   xhr.open('GET', 'http://127.0.0.1:8000/ie?t=' + Date.now())//Date.now() to get the current timestamp

2. Request timeout and networkexceptionsdeal with

Write a timer on the server sidefunction (math.)The response body is delivered to the page after three seconds.

  1. //timeout response
  2. app.get('/delay', (request, response) => {
  3. //Setting the response header Setting to allow cross-domain
  4. ('Access-Control-Allow-Origin', '*');
  5. setTimeout(() => {
  6. //Setting the response body
  7. response.send('Delayed response')
  8. }, 3000)
  9. })

You can set a timeout by making a timeout setting on the pageand timeout callbacksAnd network exception callbacks. 

  1. // timeout setting2The request is canceled if the response body is not received within seconds.
  2. = 2000
  3. //timeout callback
  4. = function () {
  5. alert('The internet isn't very good wait a little longer!')
  6. }
  7. //network anomaly callback
  8. = function () {
  9. alert('There seems to be a problem with your network')
  10. }

Manual Cancellation Request

Above by automatically canceling the request, the following describes manually canceling the request:

pass (a bill or inspection etc)()Method cancel request, the scope of the problem, the definition of xhr in the outside to give a null, and then assign the xhr instance, and then call the method. (Repeat assignment don't use const oh, use const if you can, let if you can't)

  1. <button>Click to send</button>
  2. <button>Click to cancel</button>
  3. <script>
  4. const btns = ('button')
  5. let xhr = null
  6. btns[0].onclick = function () {
  7. xhr = new XMLHttpRequest();
  8. xhr.open('GET', 'http://127.0.0.1:8000/delay')
  9. xhr.send(); //You don't have to take the response body, so you don't have to write it afterward
  10. }
  11. //Cancel request, abort method
  12. btns[1].addEventListener('click', function () {
  13. (); //nod nodding firstsenddouble-clickcancelThere will be no error, first pointcancelreport an error
  14. (xhr); //nod nodding firstsenddouble-clickcancelis the xhr instance, first clickcancelreport an error
  15. })

4. Repeated sending of requests

When the user clicks the send button several times, the judgment identifier isSending determines whether the request is being sent, if it is being sent, the request is canceled and a new request is created.

I don't know why () keeps reporting an error !!!!! (seems to bechrome(This is caused by not supporting local ajax, just change your browser)

  1. <button>Click to send</button>
  2. <script>
  3. const btns = ('button');
  4. let xhr = null;
  5. //Identifies the variable that determines whether an AJAX request is sent or not
  6. let isSending = false;
  7. btns[0].onclick = function () {
  8. // Determine the amount of markers If a request is being sent, click again to cancel the request and create a new one.
  9. if (isSending) ()
  10. xhr = new XMLHttpRequest();
  11. isSending = true;
  12. xhr.open('GET', 'http://127.0.0.1:8000/delay')
  13. xhr.send()
  14. = function () {
  15. if ( === 4) {
  16. // Modify the amount of identifiers Stop transmitting when the transmission is completed
  17. isSending = false
  18. }
  19. }
  20. }
  21. </script>