Vue基础篇-Ajax请求(axios)

1.基础知识

(a)vue2.0官方推荐使用axios,vue-resource是vue1.0时代的产物(已然下岗待业);

(b)Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中;

(c)axios基本功能包括:拦截请求和响应,转换请求数据,并发请求,取消请求,自转换JSON数据等;

(d)axios.js脚本文件需自行下载

2.基本语法

//get请求
axios.get('../data/getData',{
    params:{
        canshu001:2,
        canshu002:2
    }
}).then(function(response){
    self.dataReturn=response.data;
}).catch(function(error){
    console.log(error);
});

//post请求(注意的是传递参数的书写方法不同,没有params接受)
axios.post('../data/getData',{
    canshu001:2,
    canshu002:2
}).then(function(response){
    self.dataReturn=response.data;
}).catch(function(error){
    console.log(error);
});

3.并发请求

function getUser1() {
  return axios.get('/user/12345');
}
function getUser2() {
  return axios.get('/user/12345/other');
}

axios.all([getUser1(), getUser2()])
  .then(axios.spread(function (reg1, reg2) {
    // 两个请求执行完成,reg1为getUser1返回的结果,reg2为getUser2返回的结果
}));

4.axios的相关API

1)axios(config)   config就是配置项对象

// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

(2)axios(url[, config])    请求别名,各请求的简写模式

axios.request({data:{"name":"yin"}}).then();
axios.get("user/12345",{params:{"name":"yin"}}).then();
axios.delete("user/12345",{params:{"name":"yin"}}).then();
axios.head("user/12345",{params:{"name":"yin"}}).then();
axios.post("user/12345",{"name":"yin"}).then();
axios.put("user/12345",{"name":"yin"}).then();
axios.patch("user/12345",{"name":"yin"}).then();

(3)并发请求    axios.all([ ])发送请求    axios.spread(callback)接受结果(详情看3)

(4)请求配置config(常用)

url 请求地址 -
method 请求方式 默认:get
data 请求参数对象  
timeout 超时毫秒数 超出时间,请求将会中断
proxy 代理服务器的主机名和端口 提供允许访问的权限
cancelToken 指定用于取消请求的  

(5)响应结果

data:{} 返回结果
status:200 状态码
statusText:'OK' 状态信息
headers:{} 响应头
config:{} 请求时的配置项集合

 

猜你喜欢

转载自blog.csdn.net/qq_35892039/article/details/84107467