This is the 15th day of my participation in the August Text Challenge.More challenges in August

With Ajax

01. Ajax

What is PI (1)

  • AjaxIs a technique for creating fast, dynamic web pages
  • AjaxUsed to interact with the background
  • AjaxYou can implement a pageNo refresh Updatedata
  • AjaxThe core API provides oneXMLHttpRequestType, which is required for all AJAX operations

(2) How to do?

Create a new HTTP request
  • Specify the request’s methods, URL, and whether to process the request asynchronously: xhr.open(methods, URL, true)

    • methods: Request method
    • urlRequest address
    • boolean: Sets whether the request is executed asynchronously
      • true– asynchronous;false– synchronous

    When executed synchronously, the code is stuck at xhr.send() until all data has been transferred

    In addition, readyState will not change after all data transfer is completed

    Therefore, the onReadyStatechange event will not be fired

    • onreadystatechangeEvents, only inreadystateIt’s triggered when it changes
    • Can be found insend()Method before registering the event
Request parameters
  • GET requests: concatenated after the URL

    xhr.open("get"."Request an address?" + params)
    
    Copy the code
  • POST request: in the request body

    // application/x-www-form-urlencoded
    var params = "name=" + name + "&age=" + age 
    
    // application/json
    var params = {
        name: 'name'.age: 'age'
    }
    xhr.send(params)
    
    Copy the code
Server response
  • onload

    xhr.onload = () = > {
        let responseText = JSON.parse(xhr.responseText)
        console.log(responseText)
    }
    Copy the code
  • onReadyState

    • It’s usually inreadyState == 4The subsequent logic of the response is executed
    // Triggered when the Ajax status code changes
    xhr.onreadystatechange = () = > {
        console.log(xhr.readyState)
    }
    
    Copy the code

(3) Encapsulation

  • Basic steps
1. Create an XMLHttpRequest object
var xhr = new XMLHttpRequest()

// 2. Create a new HTTP request and specify the methods, URL, and whether to process the request asynchronously
xhr.open('GET', url, true)

// 3. Set the response header request content encoding type
xhr.setRequestHeader("Content-type"."application/x-www-form-urlencoded")

// 4. Send HTTP requests
xhr.send(null)

// 5. Obtain server response data
xhr.onreadystatechange = function () {
    if(this.readyState === 2) {// The response header is received
        console.log("HEADERS_RECEIVED", xhr.readyState)
    }else if(this.readyState === 3) {// The response body is loading
        console.log("LOADING", xhr.readyState)
    }else if(this.readyState === 4) {// Load complete
        console.log("DONE", xhr.readyState)
    }
}


Copy the code
  • methods
function ajax(options){
    // Set the default value
    var defaults = {
        type: "get".url: "".data: {},
        header: {
            "content-Type": "application/x-www-form-urlencoded"
        },
        success: function(){},
        error: function(){}};// Shallow copy. If the value of the corresponding attribute is set, the value is used. If no attribute value is set, the default value is used
    Object.assign(defaults, options)

    // Create ajax objects
    var xhr = new XMLHttpRequest()
    // Concatenate the object of the request parameters
    var params = "";
    for(var attr in defaults.data){
        // Convert arguments to string format
        params += attr + "=" + defaults.data[attr] + "&"
    }
    // Intercepts the string, cancelling the last ampersand
    params = params.substr(0, params.length-1)
    // Determine the request type
    if(defaults.type == "get") {// If it is a GET request, concatenate the parameters in the request address
        defaults.url = defaults.url + "?" + params
    }
    // Configure the Ajax object
    xhr.open(defaults.type, defaults.url)
    // Send the request
    if(defaults.type == "post") {// POST request --
        // The type of request parameter that the user wishes to pass to the server
        var contentType = defaults.header["Content-Type"]
        // The post request must set the request message
        xhr.setRequestHeader("Content-Type",contentType)
        // The POST request takes the send parameter
        // Determine the type
        if(contentType == "application/json") {// If the format is JSON, you need to convert the incoming JSON object to A JSON string
            xhr.send(JSON.stringify(defaults.data))
        }else{
            // Pass a concatenated string argument
            xhr.send(params)
        }
    }else{
        // GET request --
        xhr.send()
    }
    // Listen for the onload event
    xhr.onload = function(){
        // xhr.getresponseHeader () to get the data in the response header
        var contentType = xhr.getResponseHeader("Content-Type")
        
        // Get the data returned by the server
        var responseText = xhr.responseText
        
        // If the response type contains application/json, it is in JSON data format
        if(contentType.include("application/json")) {// Convert the data from the server-side response from JSON string format to JSON object format
            responseText = JSON.parse(responseText)
        }
        
        // Determine whether the request was successful
        if( xhr.status == 200){
            defaults.success(responseText, xhr)
        }else{
            defaults.error(responseText, xhr)
        }
    }
}

ajax({
    // Request mode
    type: "get".// Request an address
    url: "URL".// Request parameters
    data: {
        name: "Ruovan".age: 24
    },
    // Request packet type
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    // The request succeeded
    success: function(data) {
        console.log(data)
    },
    // The request failed
    error: function(data, xhr){
        console.log(data)
        console.log(xhr)
    }
})

Copy the code

02. About JSON

  • String to object:JSON.parse()
  • Object to string:JSON.stringify()

03. On the way of request

  • The GET:

    • Generally used for information retrieval, using the URL to pass parameters
    • The GET request parameters are in the URL
    • GET is faster than POST block
    • There is also a limit to the number of messages sent, typically 2000 characters
  • POST:

    • It is used to modify resources on the server
    • The request header needs to be set to specify the type of request data
    • The POST request parameter is in the request body. POST is more secure than GET
    • There are no restrictions on the information sent

  • GETThe request needs to useRequest.QueryStringTo get the value of the variable
  • whilePOSTRequest throughRequest.FormTo get the value of the variable
    • That is, Get passes values through the address bar, and Post passes values through a form submission

  • However, use a POST request in the following cases:

    • Unable to use cached files (updating files or databases on the server)
    • Sending large amounts of data to the server (POST has no data limit)
    • POST is more stable and reliable than GET when sending user input that contains unknown characters

04. On cross-domain

(1) Causes?

  • As a result of the browser’s same-origin policy, Ajax requests cannot be sent to non-same-origin addresses, and if they are requested, the browser will report an error
    • Different protocols, domain names, ports, and IP addresses may cause cross-domain problems

(2) How to solve it?

jsonp: Only GET cross-domain can be resolved
  • Create a

    All SRC and href attributes are exempt from the same origin policy and can request data content from third-party servers

    For example: external image resources, external JS files and so on

  • The server-side response data must be a function call, and the actual data to be sent to the client needs to be the parameter of the function call

// 1. Create a script tag dynamically
let script = document.createElement("script")

// 2. Set the SRC attribute of the script tag to interface address/server address with a callback function name
script.src = "Http://127.0.0.1:8888/index.php? callback=jsonpCallback"

// 3. Insert the script tag into the page
document.head.appendChild(script)

// 4. Use the callback function to receive background data
function jsonpCallback(data){
    // The data returned by jsonp is a JSON object that can be used directly
    // If the data is a JSON string obtained by Ajax, it needs to be converted into a JSON object to be used
}


Copy the code
CORSCross-domain resource sharing
  • How it works: After the server sets the access-Control-allow-originHTTP response header, the browser will Allow cross-domain requests

  • Limitations: Browsers need to support HTML5, can support POST, PUT and other methods, compatible with IE9 or above

// Set it on the server
// Allow all domain names to access
Access-Control-Allow-Origin: "*"
    
// Only specified domain names are allowed
Access-Control-Allow-Origin: "http://a.com"

Copy the code
document.domain
  • Principle:Same primary domain name different subdomain nameUnder the page, can be setdocument.domainLet them be codomain
  • Restriction: homodomaindocumentProvides interoperation between pages,Need to load theiframepage
// URL http://a.com/foo
1. Create an iframe label
var ifr = document.createElement('iframe')

// 2. Set the SRC attribute to the server address
ifr.src = 'http://b.a.com/bar'

ifr.onload = function(){
    var ifrdoc = ifr.contentDocument || ifr.contentWindow.document
    ifrdoc.getElementsById("foo").innerHTML)
};
// 4. Hide iframe
ifr.style.display = 'none'

// 5. Insert page
document.body.appendChild(ifr)

Copy the code
Apache
  • Do forwarding (reverse proxy) so that cross-domain becomes co-domain
Server resolution
  • The same-origin policy is a limitation that browsers place on Ajax technology. There is no same-origin policy restriction on the server side
  • First let client 1 send a request to server 1
  • Server 1 then accesses the data on server 2
  • Finally, the data obtained by no. 1 server responds to no. 1 client

05. About status codes

  • 2 Start status code

    • A status code that indicates that the request was successfully processed
  • Status code starting with 3

    • (Redirect) indicates that further action is required to complete the request. Typically, these status codes are used for redirects.
  • Status code starting with 4

    • Indicates that the request may be in error, preventing the server from processing it
    message = '400: Request error '
    
    message = '401: Unauthorized, please log in again '
    
    message = '403: Access denied '
    
    message = '404: Requested resource not found '
    
    message = '405: Request method not allowed '
    
    message = '408: Request timed out '
    
    Copy the code
  • Status code starting with 5

    • Code indicates an internal error occurred while the server was trying to process the request.
      • These errors may be server errors rather than request errors
      • It could also be a request parameter error that the server cannot process
    message = '500: Internal server error '
    
    message = '501: Service not realized '
    
    message = '502: Network error '
    
    message = '503: Service unavailable '
    
    message = '504: Network Timeout '
    
    message = '505:HTTP version not supported '
    
    Copy the code

    I front-end side dish chicken, if there is wrong, please forgive