What is the difference between Axios and Ajax

1. The difference between Axios and Ajax

1. Axios is a Promise-based HTTP library, and Ajax is an encapsulation of native XHR;

2. Ajax technology realizes the refresh of partial data, and Axios realizes the encapsulation of ajax.

2. The difference and advantages and disadvantages of Axios and Ajax

Ajax:

1. What is Ajax

Ajax is an encapsulation of native XHR. In order to achieve our goal of leapfrogging, support for JSONP has been added.

Asynchronous javascript and xml, ajax is not a new technology, but a combination of multiple technologies, used to quickly create dynamic pages, and can update data without refreshing to improve user experience.

2. The principle of Ajax?

The client requests the ajax engine, and then the ajax engine requests the server. After the server makes a series of responses, it returns to the ajax engine. The ajax engine decides where to write the result to the client. Realize page update data without refreshing.

3. Core object?

XMLHttpReques

4. What are the advantages and disadvantages of Ajax?

   advantage 

1. No refresh update data

2. Asynchronous communication with the server

3. Front-end and back-end load balancing

4. Widely supported based on standards

5. Separation of interface and application

   shortcoming:

1. Ajax cannot use the Back and history functions, that is, the destruction of the browser mechanism.

2. Security issues Ajax exposes the details of interaction with the server

3. The support for search engine is relatively weak

4. Break the exception handling mechanism of the program

5. Violating the original intention of URL and resource positioning

6. Ajax does not support mobile devices well

7. Too much client code causes development costs

5. Ajax application scenarios

<1>. Form-driven interaction
<2>. Deep tree navigation
<3>. Fast user-to-user communication response
<4>. Similar to voting, yes/no and other innocuous scenarios
 <5>. Yes Scenarios for filtering data and manipulating related data
<6>. Ordinary text input prompts and auto-completion scenarios

6. Ajax does not apply to scenarios

<1>. Some simple forms
<2>. Search
<3>. Basic navigation
<4>. Replace a lot of text
<5>. Manipulation of presentation

7. Code

$.ajax({
   type: 'get',
   url: '/getuser/data',
   dataType: 'json',
   data: {
        firstName: '张',
        lastName: '三'
   },
   success: function (response) {
       console.log(response);
   },
   error: function (error) {
	   console.log(error);
   }
});
<script type="text/javascript">
    function login() {
        $.ajax({
            type: 'post',
            url: '/email/login',
            dataType: 'json',
            data: {
                'account': $('#account').val(),
                'password': $('#password').val()
            },
            success: function (data) {
                if (data.code == 1) {
                    alert("登录成功");
                    window.location.href = "http://localhost:8080/email/success";
                } else {
                    alert("密码错误,请重新输入!")
                    window.location.href = "http://localhost:8080/email/error"
                }
            }
        })
    }
</script>
<script type="text/javascript">
    function addFruit() {
        let name = $.trim($("#fname").val());
        let price = $.trim($("#fprice").val());
        let count = $.trim($("#fcount").val());
        $.post("http://localhost:8080/fruit/add",
            {name: name, price: price, count: count},
            function (data) {
                if (data.code == 1) {
                    alert(data.message);
                    window.location.href = "http://localhost:8080/fruit/index";
                }
                if (data.code == 0) {
                    alert(data.message);
                }
            });
    }

    function delFruit(id) {
        if (window.confirm("是否确认删除" + id + "?")) {
            $.post("http://localhost:8080/fruit/delete?id=" + id, {id: id},
                function (data) {
                    if (data.code == 1) {
                        alert(data.message);
                        window.location.href = "http://localhost:8080/fruit/index";
                    }
                    if (data.code == 0) {
                        alert(data.message);
                    }
                });
        }
    }
</script>

8. Five steps of Ajax request

1. Create an XMLHttpRequest asynchronous object

2. Set the callback function

3. Use the open method to establish a connection with the server

4. Send data to the server

5. Handle different response states in the callback function

Axios:

1. What is Axios

Axios is a Promise-based HTTP library that can be used in the browser and node.js.

2. What features does Axios have?

1. Create XMLHttpRequests in the browser

2. Create http request in node.js

3. Support Promise API

4. Support intercepting requests and responses

5. Convert request and response data

6. Cancellation request

7. Automatically convert to JSON data format

8. The client supports defense against XSRF

3. There are two ways to execute the get request

params is used to splicing urls, get request parameters are spliced ​​into urls,

And data is placed in the request body for post requests

// 第一种写法:将参数直接写在url中
axios.get('/query?name=tom').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
// 第二种写法:将参数直接写在params中
axios.get('/query', {
    params: {
        name: 'tom'
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
// 第三种写法:将参数直接写在params中
axios({
  method: 'get',
  url: '/query',
  params: {
    name: 'tom',
  }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

4. Execute the post request, and pay attention to the input parameters of the post request, which do not need to be written in the params field. This place should be distinguished from the second method of the get request.

axios.post('/query', {
    name: 'tom',
    icon: 'img_path'
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

 The following data method puts parameters in the request body, and the backend needs to use @RequestBody + entity class to receive.

 axios({
        url: '/getUsers',
        method: 'post',
        responseType: 'json', // 默认的
        data: {
            age: 18,
            sex: '男',
        }
    }).then(function (response) {
        console.log(response);
        console.log(response.data);
    }).catch(function (error) {
        console.log(error);
    });

This method of params passing parameters is actually similar to the get request, which puts the request parameters in the request header,
http://127.0.0.1/user?age=18&sex=男
so this needs to use
@RequestParam to receive parameters

 axios({
        url: '/getUsers',
        method: 'post',
        responseType: 'json', // 默认的
        params: {
            age: 18,
            sex: '男',
        }
    }).then(function (response) {
        console.log(response);
        console.log(response.data);
    }).catch(function (error) {
        console.log(error);
    });

3. The difference between Axios and Ajax

Axios is a kind of encapsulation of ajax technology through Promise, just like jquery's encapsulation of ajax. Simply put, ajax technology realizes the refresh of partial data. Axios realizes the encapsulation of ajax. Axios has ajax. Ajax does not necessarily have axios. In a word, axios is ajax, and ajax is more than axios.

Note: Traditional Ajax refers to XMLHttpRequest (XHR), axios and jQuer ajax are both packages of Ajax.

Guess you like

Origin blog.csdn.net/qq_45037155/article/details/126829429