ajax

Ajax is Asynchronous Javascript And XML, It’s a web development technique for creating interactive web applications Ajax = asynchronous JavaScript and XML or HTML (a subset of standard Common Markup Language) Ajax is a technique for creating fast, dynamic web pages Ajax is a technique for creating dynamic web pages without having to reload the entire page, Ajax allows web pages to update asynchronously by exchanging small amounts of data in the background with the server. This means that you can update parts of a web page without reloading the entire page. Traditional web pages (without Ajax) have to reload the entire page to refer to Baidu Encyclopedia if you want to update the content

Advantages:

  1. Communicate with the server for maintenance data without page refresh, providing good user experience
  2. Asynchronous communication mode, without interrupting user operations, quick response
  3. Transfer some requests to the client and “fetch data on demand” to minimize redundant requests and the burden on the server
  4. Based on standardized and widely supported technologies, there is no need to download browser plug-ins or applets

Use:

1. Native ajax

At the heart of Ajax is the JavaScript object XmlHttpRequest

GET request mode
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest()

// Open the address to send the request. Get sends the request parameters in the URL
xhr.open("get"."https://me.csdn.net/weixin_45426836?a=1&b=2".true)

// Send the request
xhr.send()

// Listen for the request status and receive the response data, onload equals xhr.readyState == 4
xhr.onload = function(){
    if(xhr.status == 200) {
        console.log(xhr.response)  // Get the response body of the response from XHR
    }else {
    	console.log(error)
    }
}
Copy the code
POST request mode
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest()

// Open the address to which to send the request
xhr.open("post"."https://me.csdn.net/weixin_45426836".true)

// Set the request header
xhr.setRequestHeader("content-type"."application/x-www-form-urlencoded");

// To send a request, the parameters in post should be put in send
xhr.send("a=1&b=2")

Xhr. readyState == 4 = onload
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.response)  // Get the response body of the response from XHR
    }else {
    	console.log(error)
    }
}
Copy the code
The XMLHttpRequest API properties

Status: HTTP status of the response statusText: HTTP status of the response responseText: data text of the response responseXML: The onReadyStatechange: event is triggered when the xhr.readyState property changes. The onload: event is triggered when the response is received

The XMLHttpRequest API methods

Open (method, URL, async) : opens the address to which the request is to be sent. Parameters: request type, REQUEST URL, and Boolean (default true) Send (requsetBody) : Send a request (body) setRequestHeader(key, value) : sets the request header. GetResponseHeader (key) : obtains the response header

The XMLHttpRequest objectreadyStateProperty that represents the current active phase of the request response process:

0: uninitialized, XMLHttpRequest object is created, but open() method is not called 1: started, open() method has been called, but send() method has not been called 2: Sent, Send () method has been called, but no response has been received 3: Received, some response data has been received 4: Complete. All response data has been received and is ready for use on the client

2. Jquery wraps Ajax as a function$.ajax()We can use this function directly to perform ajax requests

Common parameters:

Async: indicates whether the request is asynchronous. The default value is true for asynchronous, and false for synchronous. DataType: ContentType: Application /x-www-form-urlencoded data; default: “Application /x-www-form-urlencoded” data; Error: indicates the callback function after the request fails

$.ajax({
     url: 'https://me.csdn.net/weixin_45426836'.type: 'get'.dataType: 'json'.data: {
          //'a': 1,
          //'b': 2 
     },
     success: function (data) {
         console.log(data)
     },
     error: function (err) {
     	 console.log(err)
     }
})
Copy the code
$.get()
$.get("https://me.csdn.net/weixin_45426836", {
	//'a': 1,
    //'b': 2
},function (data) {
    console.log(data)
})
Copy the code
POST request $.post()
$.post("https://me.csdn.net/weixin_45426836", {
	//'a': 1,
    //'b': 2
},function (data) {
    console.log(data)
})
Copy the code

axios

Axios is a Promise-based HTTP library that can be used in browsers and NodeJS

Advantages:

  1. Create XMLHttpRequests from the browser
  2. Create HTTP requests from Node.js
  3. Supporting Promise API
  4. Intercept requests and responses
  5. Transform request data and response data
  6. Cancel the request
  7. Automatically convert JSON data
  8. The client supports XSRF defense

Use:

The request is created by passing the relevant configuration to AXIOS
Common parameters:

BaseURL: baseURL will automatically be preceded by the URL unless the url is an absolute url responseType: Headers: user-defined request header params: URL parameter sent with the request Data: data parameter of the request, applicable only to PUT, POST, and PATCH

axios({
     url: 'https://me.csdn.net/weixin_45426836'.method: 'get'.responseType: 'json'.params: {
         //'a': 1,
         //'b': 2,
     }
}).then(function (data) {
     console.log(data)
}).catch(function (err) {
     console.log(err)
})
Copy the code
Performing a GET request
axios.get('https://me.csdn.net/weixin_45426836', {
    params: {
      //'a': 1,
      //'b': 2,
    }
}).then(function (data) {
     console.log(data)
}).catch(function (err) {
     console.log(err)
})
Copy the code
Performing a POST request
axios.post('https://me.csdn.net/weixin_45426836', {
      //'a': 1,
      //'b': 2,
}).then(function (data) {
     console.log(data)
}).catch(function (err) {
     console.log(err)
})
Copy the code
Use axios.all to process concurrent requests
function getOne() {
  return axios.get('https://me.csdn.net/weixin_45426836', {
      params: {
        //'a': 1}}); }function getTwo() {
  return axios.get('https://me.csdn.net/weixin_45426836', {
      params: {
        //'b': 2}}); } axios.all([getOne(), getTwo()]) .then(axios.spread(function (one, two) {
    console.log(one)
    cosnoel.log(two)
}))
Copy the code
Global AXIOS default

axios.defaults

// Global default baseURL
axios.defaults.baseURL = 'https://me.csdn.net/weixin_45426836'
Copy the code
Axios interceptor

Intercept requests or responses before they are processed by THEN or catch

// Add request interceptor
axios.interceptors.request.use(function (config) {
    // What to do before sending the request
    return config;
}, function (error) {
    // What to do about the request error
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // What to do with the response data
    return response;
}, function (error) {
    // Do something about the response error
    return Promise.reject(error);
});
Copy the code

The fundamental difference between Ajax and AxiOS

Axios is a wrapper around Ajax technology based on the Promise implementation. The usage of the two is basically the same, but the individual parameters are different. Axios encapsulates some simpler Ajax operations