AJAX -- Native AJAX

Native AJAX

GET request

I Example requirements: click the button, send a GET request, and render HELLO AJAX in div

  1. Create server JS file
	//1. Introduce express
	const express = require('express');
	
	//2. Create application object
	const app = express();
	
	//3. Create routing rules
	//requset is the encapsulation of request message
	//response is the encapsulation of the corresponding message
	app.get('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	
	    // Set response body
	    response.send('HELLO AJAX')
	    
	});
	
	//4. Listening port start service
	app.listen(8000, ()=>{
	    console.log("Service started,8000 Port listening...");
	})
  1. Create 1-get HTML file
<!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]
        //Binding event
        btn.onclick = function(){
            // 1. Create object
            const xhr = new XMLHttpRequest()
            const result = document.getElementById("result")
            // 2. Initialize the setting request method and url? Request parameters set later
            xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300')
            // 3. Send
            xhr.send()
            // 4. Event binding handles the results returned by the server
            // on when time 
            // readystate is an attribute in the xhr object
            // Indicates status 0 (uninitialized) 1(open method call completed) 2(send method call completed) 3 (server returned some results) 4 (server returned all results)
            // Change change
            xhr.onreadystatechange = function(){
                // Judgment (all results returned by the server)
                if(xhr.readyState === 4){
                    //Judgment response status code 200 404 403 401 500
                    // 2XX successful
                    if(xhr.status >= 200 && xhr.status < 300){
                        //Processing result line header and blank line body
                        // 1. Response line
                        // 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
                    }else{

                    }
                }
            }
        }
    </script>
</body>
</html>

Note: at this stage, if a service has been started, the original service must be closed before a new service can be started

POST request

II Example requirements: when the mouse moves over the div, send a POST request, and the results are presented in the div HELLO AJAX


  1. Modify server JS file
	//1. Introduce express
	const express = require('express');
	
	//2. Create application object
	const app = express();
	
	//3. Create routing rules
	//requset is the encapsulation of request message
	//response is the encapsulation of the corresponding message
	app.get('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	
	    // Set response body
	    response.send('HELLO AJAX')
	    
	});
	// all can accept any type of request
	app.all('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    // Response header
	    response.setHeader('Access-Control-Allow-Headers','*') //*Indicates that all types of header information are accepted
	    // Set response body
	    response.send('HELLO AJAX POST')
	    
	});
	
	//4. Listening port start service
	app.listen(8000, ()=>{
	    console.log("Service started,8000 Port listening...");
	})
  1. Create 2-post HTML file
<!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: solid 1px #903;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        // Get element object
        const result = document.getElementById("result")
        // Binding event
        result.addEventListener("mouseover", function(){
            // console.log("test");
            // 1. Create object
            const xhr = new XMLHttpRequest()
            // 2. Initialize setting type URL
            xhr.open('POST','http://127.0.0.1:8000/server')
            // Set request header 
            // Content type (predefined) is used to set the content type of the request body
            // application/x-www-form-urlencoded parameter: type of query string, fixed writing method
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            xhr.setRequestHeader('name','WEB')
            // 3. Set POST request body in send ()
            xhr.send('a=100&b=200&c=300') //Common forms
            // xhr.send('a:100&b:200&c:300')
            // xhr.send('123')
            // 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 request

III Example requirements: press the keyboard, send the request, and the result is presented in div HELLO AJAX JSON (JSON response)

1. Modify server JS file

	//1. Introduce express
	const express = require('express');
	
	//2. Create application object
	const app = express();
	
	//3. Create routing rules
	//requset is the encapsulation of request message
	//response is the encapsulation of the corresponding message
	app.get('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	
	    // Set response body
	    response.send('HELLO AJAX GET')
	    
	});
	// all can accept any type of request
	app.all('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    // Response header
	    response.setHeader('Access-Control-Allow-Headers','*') //*Indicates that all types of header information are accepted
	    // Set response body
	    response.send('HELLO AJAX POST')
	    
	});
	
	app.all('/json-server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    // Response header
	    response.setHeader('Access-Control-Allow-Headers','*') //*Indicates that all types of header information are accepted
	    // Respond to a data
	    const data = {
	        name: 'HELLO AJAX JSON'
	    }
	    //String conversion of objects
	    let str = JSON.stringify(data)
	    // Set response body
	    response.send(str)
	});
	
	//4. Listening port start service
	app.listen(8000, ()=>{
	    console.log("Service started,8000 Port listening...");
	})
  1. Create 3-json HTML file
<!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>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 keyboard press event
        window.onkeydown = function(){
            // Send request
            const xhr = new XMLHttpRequest()
            // Sets the type of response body data
            xhr.responseType = 'json'
            // initialization
            xhr.open('GET','http://127.0.0.1:8000/json-server')
            // send out
            xhr.send()
            // Event binding
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status < 300){
                        // 
                        // console.log(xhr.response);
                        // result.innerHTML = xhr.response

                        // 1. Convert data manually
                        /* let data = JSON.parse(xhr.response)
                        console.log(data);
                        result.innerHTML = data.name */


                        // 2. Automatic conversion
                        console.log(xhr.response)
                        result.innerHTML = xhr.response.name

                    }
                }
            }
        }
    </script>
</body>
</html>

nodemon auto start tool

  1. Installation: input npm install -g nodemon at the terminal
  2. Start the service: enter nodemon server js
    By installing the nodemon tool, enter commands at the terminal. In this way, when you modify the server code, you don't have to restart the service

IE cache problem

Problem: in IE browser, due to the caching mechanism, the page will not change when the value sent by the server is changed

  1. Refresh every time
  2. Specific writing method: XHR open("GET",' http://127.0.0.1:8000/ie?t= ' + Date. now())
  3. Modify server JS file
	//1. Introduce express
	const express = require('express');
	
	//2. Create application object
	const app = express();
	
	//3. Create routing rules
	//requset is the encapsulation of request message
	//response is the encapsulation of the corresponding message
	app.get('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	
	    // Set response body
	    response.send('HELLO AJAX GET')
	    
	});
	// all can accept any type of request
	app.all('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    // Response header
	    response.setHeader('Access-Control-Allow-Headers','*') //*Indicates that all types of header information are accepted
	    // Set response body
	    response.send('HELLO AJAX POST')
	    
	});
	
	app.all('/json-server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    // Response header
	    response.setHeader('Access-Control-Allow-Headers','*') //*Indicates that all types of header information are accepted
	    // Respond to a data
	    const data = {
	        name: 'HELLO AJAX JSON2'
	    }
	    //String conversion of objects
	    let str = JSON.stringify(data)
	    // Set response body
	    response.send(str)
	});
	
	// Cache for IE
	app.get('/ie', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	
	    // Set response body
	    response.send('HELLO AJAX IE')
	});
	
	//4. Listening port start service
	app.listen(8000, ()=>{
	    console.log("Service started,8000 Port listening...");
	})
  1. Create 4-IE cache problem html file
<!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 #258;
        }
    </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.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 && xhr.status <300){
                        result.innerHTML = xhr.response
                    }
                }
            }
        })
    </script>
</body>
</html>

Request timeout and network exception handling

1. Click the button. When the request exceeds two seconds, it will prompt that the request times out
2. When the network is disconnected (the second figure is set to offline), click the button to prompt that there is a problem with the network

  1. Request timeout: the client sends a request first, and the server responds to the request. If there is a problem with the software or hardware, the request may not be sent to the answer server, or it may reach the server but the server does not respond.
  2. Network exception: pronoun of network error. After network exception occurs, the browser will display error code on the type of error, such as 404 503, etc.
  3. Modify server JS file
	//1. Introduce express
	const express = require('express');
	
	//2. Create application object
	const app = express();
	
	//3. Create routing rules
	//requset is the encapsulation of request message
	//response is the encapsulation of the corresponding message
	app.get('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	
	    // Set response body
	    response.send('HELLO AJAX GET')
	    
	});
	// all can accept any type of request
	app.all('/server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    // Response header
	    response.setHeader('Access-Control-Allow-Headers','*') //*Indicates that all types of header information are accepted
	    // Set response body
	    response.send('HELLO AJAX POST')
	    
	});
	
	app.all('/json-server', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    // Response header
	    response.setHeader('Access-Control-Allow-Headers','*') //*Indicates that all types of header information are accepted
	    // Respond to a data
	    const data = {
	        name: 'HELLO AJAX JSON2'
	    }
	    //String conversion of objects
	    let str = JSON.stringify(data)
	    // Set response body
	    response.send(str)
	});
	
	// Cache for IE
	app.get('/ie', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	
	    // Set response body
	    response.send('HELLO AJAX IE')
	});
	
	// Deferred Response 
	app.get('/delay', (request, response)=>{
	    // Set response header settings allow cross domain
	    response.setHeader('Access-Control-Allow-Origin','*') //Name, value
	    setTimeout(() => {
	        // Set response body
	        response.send('HELLO AJAX Deferred Response ')
	    },3000)
	});
	
	//4. Listening port start service
	app.listen(8000, ()=>{
	    console.log("Service started,8000 Port listening...");
	})
  1. Create 5- timeout and network exception html file
<!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</title>
    <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()
            // Timeout setting 2s setting (cancel execution after two seconds)
            xhr.timeout = 2000
            // Timeout callback
            xhr.ontimeout = function(){
                alert('Network exception, please try again later!')
            }
            // Network exception callback
            xhr.onerror = function(){
                alert('There's something wrong with the 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>

Cancel request

Demand: click the send button to send the request. Click the Cancel button to cancel the request instantly. This enables manual cancellation of the request.


  1. server.js file does not change
  2. Create 6- cancel request html file
<!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 element object
        const btns = document.querySelectorAll('button')
        let x = null

        btns[0].onclick = function() {
            x = new XMLHttpRequest()
            x.open("GET",'http://127.0.0.1:8000/delay')
            x.send()
        }

        // abort method
        btns[1].onclick = function(){
            x.abort()
        }
    </script>
</body>
</html>

abort() method: you can stop the HTTP request of an XMLHttpRequest object and restore the object to its original state. For example, if an operation needs to be completed in a series of operation sequences, and any exception in it will lead to the end of the current operation. When an exception is detected in a step, use the abort() method to abort the current processing.

Duplicate request question

Problem: in order to avoid users sending the same request repeatedly, it puts great pressure on the server. You can cancel the request at 6 - Based on html, when the user repeats the request, only the latest request is retained.

  1. Create 7- duplicate request question file
<!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>Duplicate request question</title>
</head>
<body>
    <button>Click send</button>
    <script>
        // Get element object
        const btns = document.querySelectorAll('button')
        let x = null
        // Identification variable
        let isSending = false //Are AJAX requests being sent

        btns[0].onclick = function() {
            // Judgment identification variable
            if(isSending) x.abort() //If you are sending, cancel the request and create a new request
            x = new XMLHttpRequest()
            // Modify the value that identifies the variable
            isSending = true
            x.open("GET",'http://127.0.0.1:8000/delay')
            x.send()
            x.onreadystatechange = function() {
                if(x.readyState === 4){
                    // Modify identification variable
                    isSending = false
                }
            }
        }

        // abort method
        btns[1].onclick = function(){
            x.abort()
        }
    </script>
</body>
</html>

No small step can make a thousand miles. No small stream can make a river

Keywords: Javascript Front-end Ajax

Added by jp2php on Wed, 23 Feb 2022 13:46:26 +0200