Ajax detailed explanation

Time:2019-2-20

Ajax

The full name of Ajax is asynchronous JavaScript and xml. It is not a new programming language. It can be said that it is a combination of existing technologies. It is mainly used to realize the asynchronous communication effect between client and server and realize the page.Partial refreshTo create a fast dynamic web page technology.

Ajax process

- Create an XMLHttpRequest object, which is to create an asynchronous invocation object
- Create a new HTTP request and specify the method, URL, and validation information for its request
- Setting a function that responds to changes in HTTP request status
- Send HTTP requests
- Get the data returned by the asynchronous call
- Local refresh using JavaScript and DOM
Var XHR = null; // Create asynchronous objects
if(window.XMLHttpRequest){
  XHR = new XMLHttpRequest (); // IE7 + and other modern browsers
} Other if (window. ActiveXObject) {// ie6, old Opera
  xhr = new ActiveXObject('Microsft.XMLHTTP');
}
Xhr.open ('get','http://localhost:4000/test', true); //true is asynchronous and can be omitted
Xhr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); //post must be set
Xhr.onreadystatechange = function (){// If it is synchronized, this code does not need to be written. After send, use `xhr.responseText'.
    if(xhr.readyState==4 && xhr.status==200){
    /* 
    readyState
        0: Request uninitialized
        1: The server connection has been established
        2: The request has been received
        3: Request processing
        4: The request has been completed and the response is ready
    status
        200 OK
        404 Not Found
    */
      xhr.responseText;
      xhr.responseXML.children[0].children;
      JSON.parse(xhr.responseText);
    }
}
Xhr. send (String); // Used for post parameterization in the form of "a = 1 & B = 2", while get parameterization is spliced behind URL with "?".

Advantages and disadvantages

  • Advantages: It can make the page load local content without overloading the whole content, reduce data transmission, avoid users constantly refreshing or skipping pages, and improve user experience.
  • Disadvantages: Not friendly to search engines, the cost of achieving forward and backward functions under AJAX is high; cross-domain problem constraints

Ajax in jQuery

Global Ajax event handler

The jQuery library supports complete Ajax operations. All the functions and methods included here are used to load data from the server, andDoes not cause page refresh

  • $(document).ajaxComplete(handler(event, XMLHttpRequest, ajaxOptions))Register a callback function when the Ajax request is completed.

    • Whenever an Ajax request completes, jQuery triggers an ajaxComplete event, at which point all processing functions register and execute using the. ajaxComplete () method.
    • Starting with jQuery 1.8, the.AjaxComplete () method can only be bound to document elements.
    • If the global option is set to false, calling $. Ajax () or $. ajaxSetup (), the. ajaxComplete () method will not be triggered.
  • Similarly, there is an error in the requestajaxError()Before the request is sentajaxSend()The request has just begunajaxStart()When the request is completedajaxStop()When the request is successfully completedajaxSuccess()

auxiliary function

  • $.param()Create an array or object serialized string for a URL address query string or Ajax request. This method can not encode complex data structures.
  • serialize()Compiles the values used as submitted form elements into strings.
<form action="#">
    <input name="username" value="abc">
    <input name="age" value="24">
    <select name="sex">
        <option value="0">female</option>
        <option value="1">man</option>
    </select>
    <input type= "submit" value= "submit">
</form>

console.log($("form").serialize()); // username=abc&age=24&sex=0
  • serializeArray()Compiles the value used as the submitted form element into an array with name and value objects.

console.log($("form").serializeArray()); // [{name: "username", value: "abc"}, {name: "age", value: "24"}, {name: "sex", value: "0"}]

Bottom interface

  • $.ajax(url, {})or$.ajax({url: ""})With regard to parameter passing items (any default parameter can be set using $.ajaxSetup (), here are some common ones:

    • urlString, a string of URLs used to send requests
    • dataObject, String, data sent to the server. Automatically converts to request string format. The GET request will be appended to the URL.
    • dataTypeString, defaultIntelligent Guess (xml, json, script, or html))。 The expected data type returned by the server.

      • xmlhtmlscriptjsontext
      • jsonpJSON data blocks are loaded as JSONP. It automatically adds “? Callback=?” at the end of the requested URL. By default, the results are not automatically cached by appending a query string variable “=[TIMESTAMP]” to the URL unless the cache parameter is set to true.
    • acceptsPlainObject (available)$.isPlainObject()Detection), content type sending request header (Content-Type), used to inform the server what type of return result the request needs to receive. If accepts settings need to be modified, it is recommended to set them once in the $.ajaxSetup () method.
    • asyncBoolean, default true, asynchronous request
    • globalBoolean, default true. Does the request trigger global processing events (such as $(document). ajaxComplete ())
    • beforeSend(jqXHR, settings)Function, the callback function before the request is sent, is used to modify jqXHR before the request is sent. This function can be used to set custom HTTP header information. Returning false in the beforeSend function will cancel the request.
    • catchBoolean, default true, default false when dataType is “script” and “jsonp”. The principle of caching this page is to append “= timestamp” to the GET request parameters. This parameter is not required for other requests, except in IE8, when a POST requests a URL that has been requested with GET.
    • completeFunction, callback function after request completion (both call after request success and error).
    • success(data, textStatus, jqXHR)Function, call the function when the request succeeds
    • errorFunction, call function when request fails
    • timeoutNumber, set the request timeout time (milliseconds). This setting overrides the global settings in $. ajaxSetup ().
    • jsonpString, which overrides the name of the callback function in a jsonp request. This value is used to replace the “callback” part of the URL parameter in the “callback=?” GET or POST request, such as {jsonp:’onJsonPLoad’} which causes “onJsonPLoad=?” to be passed to the server. In jQuery 1.5, setting the jsonp option to false prevents jQuery from adding a URL to a “? Callback” string or trying to use “=?” conversion. In this case, you should also explicitly set the jsonpCallback settings. For example, {jsonp: false, jsonpCallback: `callbackName’}
    • jsonpCallbackString, Function, specify a callback function name for the jsonp request. This value will be used to replace the random function name generated automatically by jQuery. This is mainly used to make jQuery generate a unique function name, which makes it easier to manage requests and provide callback functions and error handling conveniently. You can also specify the callback function name when you want the browser to cache GET requests. Starting with jQuery 1.5, you can also use a function as the parameter setting, in which case the return value of the function is the result of jsonpCallback.
    • contentsPlainObject, an object paired with “{string/regular expression}”, parses the return result of the request according to the given content type.
    • contentTypeString, defaultapplication/x-www-form-urlencoded; charset=UTF-8。 Content encoding type when sending information to server.
    • contextObject, setting the context of the Ajax-related callback function. That is, to change this of the callback function, the default is the entire object passed in.
    • convertersPlainObject, default: {“* text”: window. String, “text html”: true, “text json”: jQuery. parseJSON, “text xml”: jQuery. parseXML}. An object that converts a data type to a data type. The value of each converter is a function that returns the converted request result.
    • crossDomainBoolean, the same domain request is false, and the cross-domain request is true. If you want to force cross-domain requests in the same domain (in the form of JSONP), for example, to redirect the server to another domain, you need to set crossDomain to true.
    • usernameString, User Name in Response to HTTP Access Authentication Request
    • passwordString, the password used to respond to HTTP access authentication requests
  • $. Ajax () returns the jqXHR object, which is callable

    • .done() success
    • .fail() error
    • .always() complete
    • .then()Pass in two callback functions, done and fail, respectively
  • $.ajaxPrefilter([dataTypes], handler(options, originalOptions, jqXHR) )Before each request is sent and $. Ajax () handles their preprocessing, setting custom Ajax options or modifying existing options.
  • $.ajaxSetup(options)Set default values for future Ajax requests, and subsequent AJAX requests do not set any set option parameters.

Shortcut method

  • $.get() {type: “get”}
  • $.post() {type: “post”}
  • $.getScript() {type: “script”}
  • $.getJSON() {type: “json”}
  • $(selector).load()Load the data from the server and insert the returned HTML code into the matching elements.

Jsonp in jQuery

// front end
function jsonpFn(data){
    console.log(data)
    console.log("jsonpFn");
}
$(function(){
    $.ajax({
        url: "http://localhost:3000/test",
        data: {username: "xx"},
        dataType: "jsonp",
        jsonp: "selfNamedReplaceCallback",
        jsonpCallback: "jsonpFn", // server side:req.query.callback = "jsonpFn"
        success(data){
            console.log(data)
        }
    })
})

// backend
const app = require('express').Router();
app.get('/test', (req, res, next) => {
    let name = req.query.username;
    let callback = req.query.selfNamedReplaceCallback
    let s1 = "{status: 1}"
    let s2 = `
        {
            status: 0,
            info: {
                name: "${name}",
                age: 24,
                sex: "girl",
                tel: "1522*******"
            }
        }
    `
    s1=callback+"("+s1+")"
    s2=callback+"("+s2+")"
    if(!name)return res.send(s1)
    res.send(s2)
}).listen(3000)

Axios

  • Axios is a promise-based HTTP library that can be used in browsers and node.js.
  • Creating XMLHttpRequests from Browsers
  • Create HTTP requests from node.js
  • Support for Promise API
  • Intercept requests and responses
  • Transform request and response data
  • Cancellation request
  • Automatic conversion of JSON data
  • Client Support Defense XSRF

Using Axios Demo in Vue projects

// main.js
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost/'
Vue.prototype.$axios = axios
// In. Vue file (component)
this.$axios.get("").then().catch()

this.$axios.all([
    this.$axios.post('one','content=123'),
    this.$axios.get('one?pageIndex=1')
])
.then(this.$axios.spread((res1,res2)=>{
    console.log(res1,res2)
}))
.catch(err=>{
    console.log(err)
})

The request is distributed here, and the request is executed only if it succeeds.thenThe method can be used to obtain data of provinces and cities.

// In the server.js file
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
router.get('/one',ctx=>{
    ctx.body = {
        a: 1,
        b: 2
    }
})
router.post('/one',ctx=>{
    ctx.body = {
        c: 3,
        d: 4
    }
})

app.use((ctx,next)=>{
    ctx.set("Access-Control-Allow-Origin", "*");
    ctx.body = {}
    next()
})
.use(router.routes())
.use(router.allowedMethods())
.listen(80)
Interceptor
axios.interceptors.request.use(function(ops){
    console.log(ops);
    Ops. headers = {/*...* /}; // modify before request
    Return ops; // Return unchanged location if return false intercepts directly
})

For example, the loading icon is displayed before the request succeeds and disappears after the data is obtained.

// main.js
Import Mint from'mint-ui'// Select to introduce in actual projects
import 'mint-ui/lib/style.css'
Vue.use(Mint)

axios.interceptors.request.use(function(config){
    Mint.Indicator.open()
    return config;
})
axios.interceptors.response.use(function(data){
    Mint.Indicator.close()
    return data;
})

Differences between Ajax, jQuery.ajax, Axios and Fetch

  • The earliest technology of sending back-end requests in AJAX is using XMLHttpRequest objects.
  • The $.ajax is the sending back-end request technology in jQuery, based on the encapsulation of native Ajax.
  • Axios is not native JS and needs to be installed. It can be used in both client-side and server-side. It can also be intercepted during the request and response phases. It is based on promise object.
  • Fetch, known as an alternative to AJAX, uses the promise object in ES6. Its parameters are somewhat like jQuery. ajax. However, fetch is not an encapsulation of ajax, but is implemented by native js, and does not use the XMLHttpRequest object.

Recommended Today

The method of obtaining the resolution of display by pyqt5

The code is as follows import sys from PyQt5.QtWidgets import QApplication, QWidget class Example(QWidget): def __init__(self): super().__init__() self.initUI() #Interface drawing to initui method def initUI(self): self.desktop = QApplication.desktop() #Get display resolution size self.screenRect = self.desktop.screenGeometry() self.height = self.screenRect.height() self.width = self.screenRect.width() print(self.height) print(self.width) #Show window self.show() if __name__ == ‘__main__’: #Create applications and objects app […]