Ajax basic learning

Ajax learning

  • Ajax can update the page content without refreshing the page

  • Ajax is used to check whether the user name can be used

  • The difference between XML and HTML: there are predefined tags in HTML. For example, a is the hyperlink tag, span is the inline element tag, and there are no predefined tags in XML

  • Ajax can update the contents of parts of a page (such as mouse movement) through user events

  • The disadvantage of Ajax is that it has no browsing history, can't go back, has cross domain problems, and SEO is not friendly

// Native Ajax request template
// Send request
const xhr = new XMLHttpRequest();
// initialization
xhr.open('GET', 'http://127.0.0.1:8000/json-server');
xhr.send();
xhr.addEventListener('readystatechange', () => {
    if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {

        }
    }
})

HTTP protocol

  • HTTP is a hypertext transfer protocol that specifies the parts of the request and response

  • Request message:

    • Request line: GET or POST + URL + HTTP protocol version
    • Request header: host: Baidu com´╝îCookie: name = noobming
    • Empty line: it's really empty
    • Request body GET request body is empty, POST request body can not be empty
  • Response message:

    • Response line: protocol version + corresponding status code (200) + corresponding status string ('OK ')
    • Response header: describes the content of the response body
    • Empty line: it's really empty
    • Response body: returned result
  • Check the message in google Browser: open the F12 developer tool in the browser, then go to the network option and refresh the page, you can see a pile of requests (if you can't see the requests, please refresh with F5)

    • Query String Parameters are parameters extracted from the URL of the request line for easy viewing

Install Nodejs and Express

  • First, execute npm init --yes in the workspace terminal to complete the initialization
  • Then execute npm i express to install express
  • Write express:
// Introducing express
const express = require('express');

// Create application object
const app = express();

// Create routing rule
app.get('/', (request, response) => {
    // Set simple response
    response.send('hello express');
})

// Listen to the port and start the service
app.listen(8000, () => {
    console.log("Start the service and listen to port 8000");
})
  • Execute node expresstest in the script directory js
  • Open in browser localhost:8000 Observation results

Ajax case preparation

  • You cannot start two services at the same time. Close one service first (method of closing service: Ctrl+c)
  • Others are the same as those above. There is a little change in the routing rules
// Create routing rule
app.get('/server', (request, response) => {
    // Set response header settings allow cross domain
    response.setHeader('Access-Control-Allow-Origin', '*');
    // Set response body
    response.send('hello ajax');
})
  • open localhost:8000/server Observe the response header and page text

  • readystate attribute, with States 0, 1, 2, 3 and 4 respectively

readystate property explain
0 uninitialized
1 Load (call the open method)
2 Load complete
3 Interaction (start accepting data from the server response)
4 Complete response
  • The readystatechange attribute triggers this event as soon as the status code changes, but we need to judge that the code can only be executed when readystate == 4, that is, when the data has arrived at the client
  • Full code:
const btn = document.querySelector('button');
const result = document.querySelector('#result');
btn.addEventListener('click', () => {
    // create object
    const xhr = new XMLHttpRequest();
    // initialization
    xhr.open('GET', 'http://127.0.0.1:8000/server');
    // send out
    xhr.send();
    // Event binding to handle the results returned by the server
    xhr.addEventListener('readystatechange', () => {
        // This event is executed only when the server returns all the results
        if (xhr.readyState === 4) {
            // Status code of judgment response = = 200
            if (xhr.status >= 200 && xhr.status < 300) {
                // Processing client response results
                // Corresponding line:
                console.log(xhr.status);// Status code
                console.log(xhr.statusText);// Status string
                console.log(xhr.getAllResponseHeaders());// Get all response headers
                console.log(xhr.response); // Responder
                // Sets the text to return to the page
                result.innerHTML = xhr.response;
            }
        }
    })
})
  • In this way, we get the value returned by the server without refreshing the page

  • Setting the parameters of an Ajax request

    • Add parameters after the URL, for example:? a=10&b=20

Ajax Post request

  • The open function needs to be modified for the post request
xhr.open('POST', 'http:/127.0.0.1:8000/server');
  • And you need to add a post method on the server (basically the same as the get method)
app.post('/server', (request, response) => {
    // Set response header settings allow cross domain
    response.setHeader('Access-Control-Allow-Origin', '*');
    // Set response body
    response.send('hello ajax by POST');
})
  • The parameters passed in the post request are added in the send function
xhr.send('a=100&b=200');

Ajax sets the information of the request header

  • Add method after open method
xhr.setRequestHeader('Request header','Request header value');
  • Content type: sets the request body type
  • Some custom request headers do not allow us to send (for example, name)
  • You need to add such a custom attribute in the post method of the server
// Indicates that I can accept all types of header information
response.setHeader('Access-Control-All-Headers','*');
  • Note: setHeader should be placed in front of the send method, otherwise an error will be reported
  • At this time, the browser will send an option request to determine whether it has this permission. At this time, you can change the post request to all to accept all types of requests

Ajax server response json

  • response. The send () method can only pass string type data, so it needs to convert json format data
// Data construction
const data = {
  name: 'noobming'
};
// Convert to string type
let str = JSON.stringify(data);
// Set response body
response.send(str);
  • The string obtained from the html page can be manually converted to json format
let data = JSON.parse(xhr.response);
  • Automatic conversion: setting the data type of response body

  • Set XHR on it responseType = 'json'

nodemon tool

  • nodemon automatically restarts the application

IE caching in Ajax

  • When IE receives an Ajax request, it will cache the requested data locally. When the second request is made, IE does not get the data from the server, but from the local cache (the data is not updated)
  • This problem was solved in subsequent ie versions
  • The solution is to add a timestamp parameter after the request address, so that the browser will think that this is two different requests, so that he will send a new request instead of going to the local cache
  • For example:
xhr.open("GET","http://127.0.0.1:8000/ie?t="+Date.now());

Ajax network request timeout or network exception handling

  • If the network request does not respond for more than 2 seconds, cancel the request
xhr.timeout = 2000;
  • To set the delay seconds when the network is good, you can use the setTimeout function to wrap the delay function
app.get('/delay', (request, response) => {
    // Set response header settings allow cross domain
    response.setHeader('Access-Control-Allow-Origin', '*');
    setTimeout(()=>{
        response.send('hello delay');
    },3000)
})
  • Alternatively, you can use the callback function to listen for this event
// Need to be set in advance
xhr.ontimeout = function() {
    alert('Network exception');
}
  • There are also network request failure events
xhr.onerror = function() {
    alert('network error');
}
  • Network errors can be set in the network in the developer tool in chrome. You can set the normal network speed, 3g network, or drop the line

Ajax cancel request

  • The abort() function is used in the cancellation request, and the request will be cancelled when it is used
  • Pay attention to the scope of variables. They need to be in the same object to call the function to terminate the request

Ajax repeatedly sends requests

  • When the user clicks, it will send a request to the server. Too many clicks lead to too many requests and too much pressure on the server

I thought of the principle of the throttle valve in the rotation picture

  • Solution: add a throttle valve to the local, and cancel the first unfinished request when the second same request is sent
  • Set a flag variable, change the flag to true when sending the request, and change the flag to false when readyState is 4, that is, when completing the response
  • Judge the flag. If it is true (that is, the request is being sent), cancel the previous request and send a new request
// Sending request (flag)
let isSending = false;
btns[0].onclick = function() {
    // Judge whether the identification variable is sending a request. If so, cancel the request
    if(isSending) x.abort();
    x = new XMLHttpRequest();
    isSending = true;
    x.open('GET', 'http://127.0.0.1:8000/delay');
    x.send();
    x.onreadystatechange = function() {
        if(x.readyState===4) {
            // After the request is completed, modify the identification variable
            isSending = false;
        }
    }
}

Send Ajax request in jQuery

  • Send Ajax templates in jQuery
$("button").eq(0).on("click", function () {
    $.get('http://127.0.0.1:8080/jquery-server',{a:100,b:200},function(data) {
        // The data parameter is the response body parameter
    },'json');
    // The last parameter is the response body type
})
  • The server is the same as normal

  • The difference between the get method and the post method is that the get method pastes the requested parameters after the url address, while the post request saves the parameters in the request body

  • The fourth parameter is the data format that may be returned. If you return a json in string format (json. Stringify()), if you do not add the last parameter json, it will return an ordinary string. If you add the last parameter, it will return an object in json format

  • General method Ajax

$.ajax({
    // url
    url: "http://127.0.0.1:8000/jquery-server",
    // parameter
    data: {
        a: 10,
        b: 20
    },
    // Request type
    type: "GET",
    // Responder results
    dataType: 'json',
    // Successful callback function
    success: function(data) {
        console.log(data);
    },
    // Timeout
    timeout: 2000,
    // Failed callback function
    error: function() {},
    // Setting of header information
    headers: {
        a: 100,
        b: 200
        // When using this, you need to set the cross domain of the response body
    }
})
  • On the corresponding return value, it can return successfully without converting json to string format
  • When setting cross domain requests, you need to add these two response headers to the server:
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-All-Headers', '*');

axios sends Ajax requests

  • Using cdn links to introduce axios recommendations bootCDN
  • After setting the base url, all the following URLs don't need to add the same pile in front. Just write the last part directly
// Set baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8000';
// GET request
axios.get("/axios-server", {
    // URL parameters
    params: {
        id: 100,
        name: "noobMisng"
    },
    // Request header information
    headers: {
        age: 20
    }
}).then(value => {
    // Return results
    console.log(value);
})
  • A request body parameter data (object format) is added to the post request
  • The second parameter in the post request is passed as the parameter of the request body, and the third data is other parameters
axios.post("/axios-server",{
    // Request body pass parameter (data)
    name: "noobMing",
    age: 18
},{
    // Other parameters
    params: {
        id: 100,
        name: "noobMisng"
    },
})
  • Send Ajax requests using the axios method

  • The code is as follows:

axios({
    // Request method
    method: "POST",
    // url (premise setting baseURL)
    url:"/axios-server",
    // Parameter url
    params: {
        vip: 10,
        level:20
    },
    // Header information
    headers: {
        a:100,
        b:200,
    },
    // Request body parameters
    data: {
        username:"noobMing",
        age:18
    }
}).then(response=>{
    console.log(response);
})

Send an Ajax request using the fetch function

  • fetch is a global object that can be called directly to return a promise object
  • If you want to pass the url parameter, connect directly after the url
fetch('http://127.0.0.1:8000/axios-server', {
    // Request method
    method: "POST",
    // Request header
    headers: {
        name: "noobMing"
    },
    // Request body
    body: 'username=admin'
}).then(response => {
    console.log(response);
});

Cross domain

Homologous strategy

  • Homology: the url and the url requested by Ajax must be identical in protocol, domain name and port number
  • Violating the homology policy is cross domain

jsonp solves cross domain problems

  • jsonp is an unofficial method to solve cross domain problems. It only supports get requests

  • Some tags are inherently cross domain, such as img link iframe and script

  • When implementing jsonp service with script, JavaScript code must be used as the return value before it can be received by the web page

<!-- jsonp service -->
<script src="Section to cross domain"></script>
  • The following are examples of native cross domain operations:
// Server
app.all('/result', (request, response) => {
    const data = {
        name: "noobMing"
    };
    let str = JSON.stringify(data);
    response.send(`handle(${data})`);
})
<!-- client -->
<script>
    // Processing data
    function handle(data) {
        const result = document.querySelector('#result');
        result.innerHTML = data.name;
    }
    // script tags can even be created without writing in advance
    const script = document.createElement('script');
    // Set src attribute
    script.src = 'http://127.0.0.1:8000/result';
    // Put the script tag into the document
    document.body.appendChild(script);
</script>
  • This method is equivalent to the script sending a get request to the back end. What it returns is a pre-defined function of the front end (server), which passes the data through parameters. The front end uses this function to process the passed data

Send jsonp request by jQuery

  • You need to add a url parameter when sending a jsonp request using jQuery? callback=?
$.getJSON('url',function(data){});
  • In jQuery, I feel that he doesn't need to register the function in advance without the front end. He will automatically register a function and store it in the callback parameter
// Get function
let cb = request.query.callback;
// You can write this directly when you return
response.send(`${cb}(${str})`);
// In this way, what is returned to the front end is a function, and what is stored in the data of the callback function is the data of the back end

Another solution for cross domain requests: cors

  • cors: cross domain resource sharing, which is an official solution

  • It supports get post and does not need to be changed on the client side. It is completely processed on the server side

  • This response header indicates which pages can send us requests

  • cors is to set a response header, which will mark the domain names of websites that are allowed to cross domains. Only those that are allowed can cross domains

response.setHeader('Access-Control-Allow-Origin', '*');

Tags: Javascript Ajax

Posted by cliftonbazaar on Sat, 14 May 2022 11:31:52 +0300