Understanding of http, ajax and json, encapsulation of handwritten ajax

Posted by Jeannie109 on Wed, 09 Feb 2022 05:11:29 +0100

HTTP

1. HTTP – Hypertext Transfer Protocol

1.1 HTTP three points:

  • No connection: limit each connection to one request
  • Independent: the client and server specify the MIME type of transmission, and any data type can be sent through HTTP [content type. PDF is the MIME type]
  • Stateless: it means that the agreement has no memory ability for the processing of things. The lack of status information means that the subsequent data must be retransmitted [if the subsequent operation requires the previous information, it must be retransmitted]

1.2 request method:

  • GET: it is relatively insecure and has a small amount of data transfer [address transfer]. It is generally used to request resources from the server
  • POST: it is relatively safe and has a large amount of data transmission. It can be used to store / update / transfer sensitive information to the server
  • PUT: generally used to update resources
  • DELETE: used to DELETE information

1.3 HTTP status code

  • 401: no login no login no permission
  • 408: request timeout
  • 200: success
  • 304: the use of cache is similar to that of 200, which is successful

AJAX
2.1 concept:

Asynchronous JavaScript and XML. It is a development technology for creating interactive web applications. It is a combination of multiple technologies.
[the data of the current page can be updated without refreshing the whole page]

2.2 features: the data can be updated [local update] without refreshing the whole page

2.3 what can be used for

  • Login / registration user name verification [whether there is available]
  • Login failed, do not jump to the page
  • Linkage between provinces and cities [three-level linkage]
  • Linkage on mm / DD / yy [ three-level linkage ]
  • Delayed loading of pictures

2.4 asynchronous and synchronous

  • JS execution environment - single thread: if there is only one thread, you can only do one thing. If there are multiple tasks, you must queue up. If the previous task is completed, you can perform the next operation
  • To solve this problem: JS divides tasks into synchronous and asynchronous, and puts forward asynchronous mode
  • Synchronization task: the execution order of the program is related to the code order
  • Asynchronous task: each task has one or more callback functions. After the previous task is completed, the callback function is executed instead of the latter task. The latter task will not wait for the completion of the previous task, so the execution order of the program has nothing to do with the arrangement order. Which task is completed first cannot be confirmed.

Asynchronous operation exposed

  • timer
  • event listeners
  • js built-in module for reading and writing files
  • AJAX
  • Most callback functions

2.5 AJAX principle (steps):

//Step 1: get HTTP [AJAX] object
const http;
if(window.XMLHttpRequest) { // Modern browser represented by chrome
    //new is instantiating
    http = new XMLHttpRequest();
} else if(window.ActiveXObject) {   // Internet Explorer
    http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
    console.log("The current browser does not support!");
};

   //Step 2: change of monitoring status
http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200 && http.status <= 300 || http.status == 304) {
        // Request succeeded
    } else {
        console.log("Request failed!");
    }
}

//improvement
http.onreadystatechange = function() {
    if(http.readyState == 4) {
        if(http.status == 200) {
            // Request succeeded
        } else if(http.status == 401) {
            // No permission
        } else if(http.status == 404) {
            // Resource does not exist
        } else if(http.status == 500) {
            // Server error
        }
    } else {
        console.log("request was aborted");
    }
}
 /*
 readyState Change steps:
0: Uninitialized, i.e. no call to open () -- Ajax object creation completed
1: open() has been called, but send() has not been called -- data sending succeeded
2: send() has been called but no response has been received -- raw data reception
3: All response headers have been received, but the response body is receiving-- Parse data
4: Completed, all response data have been accepted-- Parsing completed (represents that the real parsing is completed and debugging is completed)
 */


//Step 3: request type
http.open(Request type,Request address,Synchronous or asynchronous);


//Step 4: send request
http.send(Requested data carried);
//Example: http send(data);

3,jQuery AJAX

/*
$.ajax({
    url: Request address,
    method:Request method, type used before version 1.9.0,
    data: Data sent to the server, key value pairs, strings, objects,
    dataType: Expected data type returned by the server (json,html file, txt file) [can be specified here]
    contentType: Default application/x-www-form-urlencoded -- form data format
    Cross domain Related settings
});

$.get();
$.post();

$(Element) load();  Request an html fragment back
*/

JSON

1. JSON data format: --- lightweight data exchange format. Is a subset of js object syntax.

2. Syntax format

  1. The entire JSON is wrapped in curly braces {}
  2. Data is stored in key value pairs, [Note: attribute names must be enclosed in double quotation marks]
  3. The value can be any value, null string [must be enclosed in double quotation marks] Boolean numeric array object
  4. Key value pairs are separated by commas
  5. JSON absolutely [no comment]
  6. JSON suffix is json
    3. Method:
  • JSON.parse(jsonString); Convert json string to json object
  • JSON.stringify(obj); Convert json object to json string
const users = {
    "username": "jack",
    "userpass": "123456"
}
//Convert to string
const userStr = JSON.stringify(users);
console.log(typeof userStr);
console.log(userStr);
// Convert to JSON object
const userObj = JSON.parse(userStr);
console.log(userObj)

Below is an encapsulated AJAX call method (GET or POST),

/**
 * 
 * @param {Encapsulated AJAX call method} options 
 * options {
 *  method:"POST", - GET Or POST transmission mode
    url:"http://xx.xx.xx.xx:8888/pub.getLogin", - url address to
    data:{identity:"MANAGER",account:"fairy",password:"123456"}, - Parameters to be passed
 * }
 * @returns 
 */
function ajax (options) {
    //URL refers to the interface address. Here is the complete address. If dynamic splicing is required, the front address is the same and the back address is different. For example:“ http://xx.xx.xx.xx:8888/ "+ options.url"
    let url = options.url
    const method = options.method.toLocaleLowerCase() || 'get'
    const async = options.async != false // default is true
    const data = options.data;
    const xhr = new XMLHttpRequest()
    if (options.timeout && options.timeout > 0) {
        xhr.timeout = options.timeout
    }
    return new Promise ( (resolve, reject) => {
        xhr.ontimeout = () => reject && reject('request timeout') //Why is it not shown in the front? 
        // xhr. ontimeout = () => console. Log ('request timeout ')// You can print it out
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                    // Data processing when the interface connection is successful
                    // First convert the returned string to json format
                    let result = JSON.parse(xhr.responseText)
                    // If the interface returns an error message, error will be printed out (processing the error message can be a prompt, which is used here for printing)
                    if(result.error) {
                        console.log(result.error)
                    } else {
                        // If the interface returns correct data without error prompt, call the callback function to return correct information, and the returned information also needs to be updated
                        resolve && resolve(result)
                    }
                } else {
                    // When interface connection fails
                    reject && reject('request was aborted')
                    console.log("Interface connection failed")
                }
            }
        }
        xhr.onerror = err => reject && reject(err)
        let paramArr = []
        //If the transmission mode is GET, the data needs to be spliced to the url address
        if (method === 'get') {
            let encodeData
            if (data instanceof Object) {
                for (let key in data) {
                    // Parameter splicing needs to be encoded through encodeURIComponent
                    paramArr.push( encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) )
                }
                encodeData = paramArr.join('&')
            }
                 // Detect whether the url already exists? And its location
                const index = url.indexOf('?')
                if (index === -1) url += '?'
                else if (index !== url.length -1) url += '&'
                  // Splice url
                url += encodeData
        }
        xhr.open(method, url, async)
        // Judge whether the transmission method is get or post. If it is get, the send data is null. If it is post, the data will be transferred into json string. The data of get has been processed above
        if (method === 'get') xhr.send(null)
        else {
            // The request header needs to be set for post mode
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
            xhr.send(JSON.stringify(data))
        }
    } )
}

usage method

//Example: how to call ajax
var option={
        method:"POST",//Data transmission mode: GET/POST
        url:"http://xx.xx.xx.xx:8888/pub.getLogin ", / / interface address
        data:{identity:"MANAGER",account:"fairy",password:"1234"},//Transmission parameters
}
ajax(option).then((result) => {
        // Processing after success
        console.log("success",result);
});

Topics: Javascript Ajax