通过vue实现get请求、post请求-----------各2种方式
axiso文档:http://www.axios-js.com/zh-cn/docs/index.html
使用GET请求
第一种使用纯url拼接方式
get1_:function() {
axios.get('/ajax/get?id=1&name=xcc')
.then(function (response) {
console.log(response.data.data);
})
.catch(function (error) {
console.log(error);
});
},
第二种使用传递参数的形式
get2_:function() {
axios.get('/ajax/get',{
params:{
id:1,
name:'xcc'
}
}).then(function (response) {
console.log(response.data.data);
}).catch(function (error) {
console.log(error);
});
},
后台参数接收
@GetMapping("/get")
public Map<String,Object> testGet(String id,String name){
Map<String,Object> map = new HashMap<>();
User user = new User();
user.setId(id);
user.setName(name);
map.put("status",0);
map.put("msg","请求成功");
map.put("data",user);
return map;
}
使用POST请求
第一种使用Form Data形式传递
post1_:function () {
axios.post('/ajax/post', {
id: '1',
name: 'abc'
},{
transformRequest: [function (data) {
let params = '';
for(let i in data){
params+=i+"="+data[i]+"&";
}
return params.substring(0,params.length-1);
}],
}).then(function (response) {
console.log(response.data.data);
}).catch(function (error) {
console.log(error);
});
},
后台接收参数
@PostMapping("/post")
public Map<String,Object> testPost(User user){
Map<String,Object> map = new HashMap<>();
map.put("status",0);
map.put("msg","请求成功");
map.put("data",user);
return map;
}
第二种使用JSON请求
post2_:function () {
axios.post('/ajax/post2', {
id: '2',
name: 'abc'
}).then(function (response) {
console.log(response.data.data);
}).catch(function (error) {
console.log(error);
});
}
后台必须使用@RequestBody接收
@PostMapping("/post2")
public Map<String,Object> testPost2(@RequestBody User user){
Map<String,Object> map = new HashMap<>();
map.put("status",0);
map.put("msg","请求成功");
map.put("data",user);
return map;
}