Home >Web Front-end >JS Tutorial >How to operate ajax request and axios package

How to operate ajax request and axios package

php中世界最好的语言
php中世界最好的语言Original
2018-06-07 11:18:041711browse

This time I will show you how to operate ajax requests and axios packages, and what are the precautions for operating ajax requests and axios packages. The following is a practical case, let's take a look.

In vue, data requests are often used. Commonly used ones are: vue-resourse, axios

Today I am talking about axios post request

github source file and document address: [https://github.com/axios/axios]

First, introduce axios

CDN: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
npm: npm install axios   并在全局的js中引入:import axios from 'axios';

• get request

axios.get('/user?ID=12345')
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });

•post request

 依赖于qs包,将对象转换成以&连接的字符串
//例:
axios.post( postUrl ,qs.stringify({userid:1,username:'yyy'})).then(function (response) {
  console.log(response);
})

Appendix: Configuring axios

In the method encapsulated above, three configuration items of axios are used. In fact, only the url is required. For the complete api, please refer to the instructions for use.

For convenience, axios also has aliases for each method, such as The above saveForm method is equivalent to:

axios.post('/user', context.state.test02)

The complete request should also include .then and .catch

.then(function(res){
 console.log(res)
})
.catch(function(err){
 console.log(err)
})

When the request is successful, .then will be executed, otherwise .catch

will be executed.

These two callback functions have their own independent scopes. If you access this directly inside, you cannot access the Vue instance

At this time, just add a .bind(this) to solve this problem

.then(function(res){
 console.log(this.data)
}.bind(this))

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to operate echarts node to display dynamic data

Use vue .sync modifier in the project

The above is the detailed content of How to operate ajax request and axios package. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn