axios发送请求的方式
axios发送请求的方式
·
axios的基本用法
axios是一个ajax框架,简化了各种ajax操作,有强大的ajax操作功能。
get请求
语法:
axios.get(‘url’, [params]) // url和参数
. then(function(res){}) // 回调
.catch(function(ex){}); // 异常捕获
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 此处then方法也可以写为:
axios.get('/user?ID=12345')
.then(res => {
console.log('数据是:', res);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
post请求
语法:
axios.post(‘url’, paramobj) // url和参数
. then(function(res){}) // 回调
.catch(function(ex){}); // 异常捕获
注意:此处请求与jQuery完全不同。
jQuery如果按照此处直接传json对象的参数的话,后台应该使用request.getParameter方式接收,也就是说默认为表单提交类型,即application/x-www-form-urlencoded,如果是对象,后台springmvc中直接使用对象接收即可。
axios如果直接传json对象,默认认为是json格式传参,即application/json,也就是以流的形式提交,后台必须使用@RequestBody方式接收参数。
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
如果想使用普通的post传参,有两种方式:
// 1、使用?号
axios.post("http://localhost:8080/add?id=3&name=mary&sex=n").then(function(resp){
if(resp.data.code == "10000"){
alert(JSON.stringify(resp.data.data));
}else{
alert(resp.data.desc);
}
});
// 使用params
// 如果使用普通的post传参,需要使用第三个参数才能用params的方式
axios.post("http://localhost:8080/add", null, {
params:{
id:2,
name:"张三",
sex:"男"
}
}).then(function(resp){
if(resp.data.code == "10000"){
alert(JSON.stringify(resp.data.data));
}else{
alert(resp.data.desc);
}
});
并发请求
// 执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
更多推荐
已为社区贡献1条内容
所有评论(0)