ajax notes_ 01_ Native ajax

Posted by Liodel on Thu, 27 Jan 2022 04:39:11 +0100

Chapter 1 native AJAX

Introduction to AJAX

  • The full name of AJAX is asynchronous JavaScript and XML, which is the JS and XML of asynchronous requests.

  • Through AJAX, you can send asynchronous requests to the server in the browser. The biggest advantage is to obtain data without refresh

  • AJAX is not a new programming language, but a new way to combine existing standards

Introduction to XML

  • XML extensible markup language

  • XML is designed to transmit and store data

  • XML is similar to HTML. The difference is that HTML has predefined tags, while XML has no predefined tags. They are all custom tags to represent some data

    For example, one of my students is the data: name: "Monkey King"; age=18; gender = "male"

    Expressed in XML

    <student>
        <name>Sun WuKong</name>
        <age>18</age>
        <gender>male</gender>
    </student>
    
  • Now it has been replaced by JSON

    Represented by JSON

    {
        "name":"Sun WuKong",
        "age":18,
        "gender":"male"
    }
    

AJAX features

AJAX is a little

  1. It can communicate with the server without refreshing the page
  2. Allows you to update some page content based on user events

Disadvantages of AJAX

  1. No browsing history, can't go back
  2. There are cross domain problems
  3. SEO is unfriendly

HTTP protocol

HTTP

(hypertext transport protocol) protocol [hypertext transport protocol], which specifies the rules for mutual communication between browsers and World Wide Web servers

Agreement, rule

Request message

The focus is on format and parameters

The request message has four parts:

  1. that 's ok
  2. head
  3. Empty line
  4. body
partdetails
that 's okRequest mode, path, protocol version, POST /s?ie=utf-8 HTTP/1.1
headHOST:value Cookie:value Content-type:value User-Agent:value
Empty lineFixed, must have
bodyThe request body is empty in GET request, and can not be empty in POST request

response message

The response message also has four parts:

  1. that 's ok
  2. head
  3. Empty line
  4. body
partdetails
that 's okProtocol version response status code response status string HTTP/1.1 200 OK
headSame as the request header of the request message
Empty lineFixed, must have
bodyResults returned from the server

Installation and basic use of express

Installation (requires node environment)

Initialization item: npm init --yes

Installing the express framework: npm i express

Basic use

// 1. Reference express
const express = require('express')

// 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
app.get('/', (request, response) => {
  // Set response
  response.send('HELLO EXPRESS')
})

// 4. Listening port start service
app.listen(8000, () => {
  console.log("The service has been started and port 8000 is listening")
})

Use of AJAX

GET request

The server:

// Introducing express
const express = require('express')

// create object
const app = new express()

// Create routing rule
app.get('/server', (request, response) => {
  // Set the response header to allow cross domain
  response.setHeader('Access-Control-Allow-Origin', '*')

  // Set response body
  response.send('HELLO AJAX')
})

// lsnrctl start 
app.listen(8000, () => {
  console.log('The server has been started. Port 8000 is listening...','GET request')
})

Page and AJAX request sending:

<!DOCTYPE html>
<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 button element
    const btn = document.getElementsByTagName('button')[0]
    const result = document.getElementById('result')

    // Binding event
    btn.onclick = function() {
      // 1. Create object
      const xhr = new XMLHttpRequest()
      // 2. Initialize and set the request method and url
      xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200')
      // 3. Send
      xhr.send()
      // 4. Event binding to handle the results put back by the server
      // When
      // readystate is a property in the xhr object that represents the state 0 1 2 3 4
      // The meaning of change
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          // Judgment response status code 200 404 403 401 500
          // The beginning of 2 is successful
          if (xhr.status >= 200 && xhr.status < 300) {
            // Processing result line header and blank line body
            // response
            console.log(xhr.status) // Status code
            console.log(xhr.statusText) // Status string
            console.log(xhr.getAllResponseHeaders()) // All response headers
            console.log(xhr.response) // Responder

            // Set the text of the result
            result.innerHTML = xhr.response
          }
        }
      }
    }
  </script>
</body>

</html>

POST request

The server:

// Introducing express
const express = require('express')

// create object
const app = new express()

// Create routing rule
app.get('/server', (request, response) => {
  // Set the response header to allow cross domain
  response.setHeader('Access-Control-Allow-Origin', '*')

  // Set response body
  response.send('HELLO AJAX')
})

app.post('/server', (request, response) => {
  // Set the response header to allow cross domain
  response.setHeader('Access-Control-Allow-Origin', '*')

  // I can accept all response headers
  response.setHeader('Sccess-Control-Allow-Headers', '*')
  
  // Set response body
  response.send('HELLO AJAX')
})

// lsnrctl start 
app.listen(8000, () => {
  console.log('The server has been started. Port 8000 is listening...','POST request')
})

Page and AJAX request sending:

<!DOCTYPE html>
<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 POST request</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: 1px solid #903;
    }
  </style>
</head>
<body>
  <div id="result"></div>

  <script>
    // Get element object
    const result = document.getElementById('result')

    // Binding event
    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')
      // Set request header
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
      
      // 3. Send (carry parameters)
      xhr.send('a=100&b=200')
      // 4. Event binding
      xhr.onreadystatechange = function() {
        // judge
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            // Process the results returned by the server
            result.innerHTML = xhr.response
          }
        }
      }
    })
  </script>
</body>
</html>

JSON response

The server:

const express = require('express')

const app = new express()

// Create routing rule
app.get('/server', (request, response) => {
  response.setHeader('Access-Control-Allow-Origin', '*')

  // Respond to a data
  let data = {
    name:'Soli',
    age:17
  }
  // String conversion of objects
  let strData = JSON.stringify(data)
  // Set response body
  response.send(strData)
})


app.listen(8000, () => {
  console.log('The server has been started. Port 8000 is listening...','JSON response')
})

Page and AJAX request sending:

<!DOCTYPE html>
<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>
  <div id="result"></div>

  <script>
    const result = document.getElementById('result')

    // Bind keyboard press event
    window.onkeydown = function() {
      const xhr = new XMLHttpRequest()

      // Sets the type of response body data
      // If it is set to json, there is no need to manually convert the data of the server
      xhr.responseType = 'json'

      xhr.open('GET', 'http://127.0.0.1:8000/server')
      xhr.send()
      // Event binding
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            // 1. Convert data manually
            // let data = JSON.parse(xhr.response)
            // result.innerHTML = data.name + data.age

            // 2. Automatic data conversion
            result.innerHTML = xhr.response
          }
        }
      }
    }
  </script>
</body>

</html>

IE cache problem

The server:

// Introducing express
const express = require('express')

// create object
const app = new express()

// Create routing rule
app.get('/server', (request, response) => {
  // Set the response header to allow cross domain
  response.setHeader('Access-Control-Allow-Origin', '*')

  // Set response body
  response.send('HELLO AJAX')
})

// lsnrctl start 
app.listen(8000, () => {
  console.log('The server has been started. Port 8000 is listening...','IE Cache problem')
})

Page and AJAX request sending:

<!DOCTYPE html>
<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>IE Cache problem</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: solid 1px #90b;
    }
  </style>
</head>

<body>
  <div id="result"></div>

  <script>
    const result = document.getElementById('result')

    result.addEventListener('click', function() {
      const xhr = new XMLHttpRequest()

      // To solve the caching problem of IE, you only need to add a timestamp when requesting
      xhr.open('GET', 'http://127.0.0.1:8000/server?t='+Date.now())
      xhr.send()
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            result.innerHTML = xhr.response
          }
        }
      }
    })
  </script>
</body>

</html>

Request timeout and network exception handling

The server:

// Introducing express
const express = require('express')

// create object
const app = new express()

// Create routing rule
app.get('/server', (request, response) => {
  // Set the response header to allow cross domain
  response.setHeader('Access-Control-Allow-Origin', '*')

  // Set response body
  // response.send('HELLO AJAX')

  // Send the response body with a delay of 2s
  setInterval(()=>{
    response.send('HELLO AJAX')
  }, 3000)
})

// lsnrctl start 
app.listen(8000, () => {
  console.log('The server has been started. Port 8000 is listening...', 'Request timeout and network exception handling')
})

Page and AJAX request sending:

<!DOCTYPE html>
<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>Request timeout and network exception handling</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 button element
    const btn = document.getElementsByTagName('button')[0]
    const result = document.getElementById('result')

    // Binding event
    btn.onclick = function() {
      const xhr = new XMLHttpRequest()

      // Timeout setting
      // Request more than 2s interrupt request
      xhr.timeout = 2000

      // Set callback for timeout
      // Call this method when timeout occurs
      xhr.ontimeout = function() {
        alert('The request timed out. Please try again later')
      }

      // Network exception callback
      xhr.onerror = function() {
        alert('There seems to be something wrong with your network')
      }

      xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200')
      xhr.send()
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            result.innerHTML = xhr.response
          }
        }
      }
    }
  </script>
</body>

</html>

Cancel request

The server:

// Introducing express
const express = require('express')

// create object
const app = new express()

// Create routing rule
app.get('/server', (request, response) => {
  // Set the response header to allow cross domain
  response.setHeader('Access-Control-Allow-Origin', '*')

  // Delayed response
  setTimeout(() => {
    response.send('HELLO AJAX')
  }, 3000);
})

// lsnrctl start 
app.listen(8000, () => {
  console.log('The server has been started. Port 8000 is listening...', 'Cancel request')
})

Page and AJAX request sending:

<!DOCTYPE html>
<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>Cancel request</title>
</head>

<body>
  <button>Click send</button>
  <button>Click Cancel</button>

  <script>
    // Get button element
    const btns = document.querySelectorAll('button')

    // Define the object outside the two functions
    let xhr = null

    // Click send request
    btns[0].onclick = function() {
      xhr = new XMLHttpRequest()
      xhr.open('GET', 'http://127.0.0.1:8000/server')
      xhr.send()
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && status < 300) {
            console.log(xhr.response)
            console.log('Request succeeded')
          }
        }
      }
    }

    // Click Cancel to send the request
    btns[1].onclick = function() {
      xhr.abort()
      console.log('Cancel the sending of the request');
    }
  </script>
</body>

</html>

Repeated sending of AJAX request

The server:

const express = require('express')

const app = new express()

app.get('/server', (request, response) => {
  response.setHeader('Access-Control-Allow-Origin', '*') // Allow cross domain
  setTimeout(()=>{
    response.send('HELLO AJAX')
  }, 3000)
})

app.listen(8000, () => {
  console.log('The server is started successfully, and the port number is 8000','')
})

Page and AJAX request sending:

<!DOCTYPE html>
<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 Request repeat issue</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: 1px solid #903;
    }
  </style>
</head>
<body>
  <div id="result"></div>
  <script>
    // Get element
    const result = document.querySelector("#result")
    const xhr = null

    // Identification variable
    // Indicates whether the request is being sent at this time
    let isSending = false
    result.addEventListener('click', function() {
      // Judgment representation variable
      if (isSending) { // If sending. Cancel the request and create a new request
        xhr.abort()
      }
      
      xhr = new XMLHttpRequest()

      isSending = true // Modify identification variable
      xhr.open('GET', 'http://127.0.0.1:8000/server')
      xhr.send()
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          // Modify identification variable
          // If the status code is 4, you can modify it, because this request may be a failed request
          isSending = false

          if (xhr.status >= 200 && xhr.status < 300) {
            result.innerHTML = xhr.response
          }
        }
      }
    })
  </script>
</body>
</html>

Topics: Javascript Front-end Ajax