The use of axios and ajax, the difference between axios and ajax

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

AJAX is not a new programming language, but a new way of using existing standards. Its biggest advantage is that it can exchange data with the server and update part of the web page content without reloading the entire page. No browser plug-ins are required, but users are required to allow JavaScript to execute on the browser.

Axios is an encapsulation of ajax technology through the promise of es6, just like jQuery implements ajax encapsulation. We also use Ajax encapsulated by jQuery, and rarely use native Ajax. Without further ado, let's serve the dishes directly.


axios use

//安装
npm install axios -S

//导入
import axios from "axios";

Directly used, the get request parameter is params, and the post request parameter is data.

 axios({
        url: 'http://127.0.0.1:8000/',                 //1、请求地址
        method: 'get',                                 //2、请求方法
        params: params,                                //3、get请求参数
        })
        // 2、回调函数
        .then(res => {
         console.log(res);
         })
         // 3、捕获异常
         .catch(err => {
           console.log(err);
         });
       }

Axios secondary packaging

Create request.js, import axios, and create a global axios instance

export function request(config){
    //创建axios实例
        const instance = axios.create({
        baseURL: 'http://127.0.0.1:8000/',
        timeout: 5000,
        // headers: header  
        })
        //axios拦截器
        //axios拦截器
        //请求拦截
        instance.interceptors.request.use(config => {
            return config
        },err => {
            console.log(err);
        })
        //响应拦截
        instance.interceptors.response.use(res => {
            return res.data
        },err => {
            console.log(err);
        })
        //发送网络请求
        return instance(config)
}

 Create api.js, import request, create request method

import {request} from './request'

export function getdata(params) {
    return request({ 
        url:'/api/data',
        method: 'GET',
        params
    })
}

Send a request to get data

import {getdata} from "../../api.js"

mounted(){
    getdata(params)
    .then(res => {
        console.log(res);
    })
    .catch(err => {
       console.log(err);
    });
}

Axios has a request interceptor and a response interceptor. We can add globally required fields or set animations before the request, and we can also process various codes agreed with the backend in the response interceptor.

When using axios, it is generally used for secondary packaging, which is convenient for management.


ajax use

Generally, when using Ajax, it is used like this:

$.ajax({
    type:'get',            //或post
    url:url,
    data:{},
    //dataType: ''        //预期后端返回数据类型:json、xml、html等
    success:function(data) {
    },
    error:function() {
        
    },
    complete:function() {

    },
})

The use of Ajax is rarely repackaged and used directly.

The following is a simple package of ajax:

const apiurl = function (url) {
                return '' + url;
            }
            const ajaxConnect = (type,url,data,callBack) => {

            var data = data || {};
            $.ajax({
                type:type,
                url:apiurl(url),
                data:data,
                success:function (data) {
                if(data.code == 10000){

                }else{

                    callBack(data.data);

                }       

                },
                error:function (data) {
                    
                }
            })
        };

When calling:

ajaxConnect('post','','',function (data) {
    
})

In addition to these parameters, Ajax has a lot of parameters, such as file transmission, synchronous or asynchronous, etc., which can be encapsulated if necessary, but I personally think that those that are rarely used, it is better to rewrite Ajax when needed.


ajax:

1. It is programming for MVC, which does not conform to the current wave of front-end MVVM

2. Based on native XHR development, the structure of XHR itself is not clear.

3. The whole project of JQuery is too big. It is very unreasonable to introduce the whole JQuery by simply using ajax (the personalized package solution can not enjoy CDN service)


axios:

1. Create an XMLHttpRequest from the browser

2. Support Promise API

3. The client supports preventing CSRF

4. Create http request from node.js

5. Intercept requests and responses

6. Transform request and response data

7. Automatically convert JSON data


If there is any error in the description, please correct me!

Guess you like

Origin blog.csdn.net/m0_70015558/article/details/126137583