Problem: Too much code for sending one Ajax request and redundant and repetitive code for sending multiple requests

Solution: Encapsulate the request code into a function that can be called when the request is sent

1, simple version

function ajax(mether, url, callback, data, flag) {
    // Whether asynchronous, default asynchronous
    flag = flag || true;
    let xhr;
	
    // Request method is converted to uppercase
    mether = mether.toUpperCase();
    
    // Resolve compatibility issues
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest()
    } else if (window.ActiveXObject) {
        xhr = new ActiveXObject()
    }
    
    // Response content
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            callback(xhr.responseText)
        }
    }
    ` `
	// If it is a GET request
    if (mether === 'GET') {
        let date = new Date(a);let timer = date.getTime();
        xhr.open("GET", url + '? ' + data + '&timer' + timer, flag);
        xhr.send()
    
        // If it is a POST request
    } else if (mether === 'POST') {
        xhr.open('POST', url, flag);
        xhr.setRequestHeader('Content-Type'."application/x-www-form-urlencoded");
        xhr.send(data)
    }
}
Copy the code

Note: Time parameters are added to get requests to address caching issues

Ajax has serious caching problems in earlier versions of Internet Explorer. With the request address unchanged, only the first request is actually sent to the server, with subsequent requests fetching results from the browser’s cache. As a result, even if the server updates the data, the client still gets the old data in the cache

The solution is to request parameters after the request address, ensuring that the value of the request parameters is different in each request

So add real-time time to each send so that the request parameters are different each time

2, detailed version

The above simplified version is data-processed by default, that is, it handles the data itself when it is passed in

This method adds methods for request success and request failure

function Ajax(options) {
    // Default parameters
    let defaults = {
        method: 'GET'.url: ' '.data: {},
        header: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function() {},
        error: function() {}}// options replaces the same properties in defaults
    Object.assign(defaults, options)
	
    // Request in uppercase
    defaults.method = defaults.method.toUpperCase()

    let xhr;
    // Resolve compatibility
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xhr = new ActiveXObject();
    }

    // Listen to the request process
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            // Get the response header data
            let contentType = xhr.getResponseHeader('Content-Type');
            // Get the response data
            let contentText = xhr.responseText;

            // If the server returns a JSON string, it needs to be converted to a JSON object
            if (contentType === 'application/json') {
                contentText = JSON.parse(contentText)
            }

            // Call success when the HTTP status code is 200
            if (xhr.status === 200) {
                defaults.success(contentText, xhr)
                // Otherwise call error
            } else {
                defaults.error(contentText, xhr)
            }
        }
    }

    // Splice request parameters namer= Xue Zhiqian &song= just right
    let params = ' '
    for (let key in defaults.data) {
        params += key + '=' + defaults.data[key] + '&'
    }
    // Remove the last character &
    params = params.substr(0, params.length - 1);

    // If it is a GET request
    if (defaults.method === 'GET') {
        // The request address needs to be concatenated
        defaults.url = defaults.url + '? ' + params;
    }
    
    // Configure the request mode and path
    xhr.open(defaults.method, defaults.url)

    // If it is a POST request
    if (defaults.method === 'POST') {
        let contentType = defaults.header['Content-Type'];
        // Set the request header
        xhr.setRequestHeader('Content-Type', contentType);
        // If you want to send a JSON object, convert the JSON object to a JSON string
        if (contentType === 'application/json') {
            xhr.send(JSON.stringify(defaults.data))
                // If the data sent is not a jSON object
        } else {
            xhr.send(params)
        }

        // If it is not a POST request, send a GET request
    } else{ xhr.send(); }};Copy the code

The biggest difference between A GET request and a POST request is the way data is sent

  • GETA request is a concatenation of data with the request address
  • POSTThe request is to pass data tosend()Send to the server

What they have in common is that the data needs to be concatenated to the form namer=xxx&age= XXX

The POST request, however, requires a header:

xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
Copy the code

To send data as a JSON string, you need to convert a JSON object to a JSON string. A POST request is required

JSON.stringify(JSONObject)Copy the code

Call wrapped Ajax functions:

Prerequisite: You need to import this function first

Ajax({
    // Request mode
    method: 'post'.// Request an address
    url: 'http://localhost:3000/cache'.// Send data as JSON objects
    header: {
        'Content-Type': 'application/json'
    },
    data: {
        namer: 'Xue Zhiqian'.song: 'Just right'
    },
    success: function(data, xhr) {
        console.log('Request successful');
        console.log(data);
        console.log(xhr);
    },
    error: function(data, xhr) {
        console.log('Request failed');
        console.log(xhr);
        console.log(xhr.getResponseHeader); }});Copy the code