Vue中如何实现ajax请求,VUE中如何发ajax请求

vue中是推荐使用axios来发送请求的。而且在vue2.0之后也是使用axios来实现发送ajax请求的。

1. 安装

axios有好几种引用的方式,其中主要包括如下:

使用 cdn:

使用npm

$ npm install axios

使用 bower:

$ bower install axios

使用

1.get请求

mounted: function() {

axios

.get('http://www.mycart.com:7772/allItems')

.then(response => (

this.items = response.data))

.catch(function (error) { // 请求失败处理

console.log(error);

});

}

带有参数的形式

// 直接在 URL 上添加参数 ID=12345

axios.get('/user?ID=12345')

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

// 也可以通过 params 设置参数:

axios.get('/user', {

params: {

ID: 12345

}

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

2. post请求

let formData = new FormData();

//下面是表单绑定的data 数据

formData.append('skuId', item.skuId);

formData.append('quantity',1);

axios

.post("http://www.mycart.com:7771/cart",formData)

.then(resp=>{

alert("商品添加购物车成功!");

})

.catch(function (error) { // 请求失败处理

alert("商品添加购物车失败");

});

也可以这样传递参数

axios.post('/user', {

firstName: 'Fred', // 参数 firstName

lastName: 'Flintstone' // 参数 lastName

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

跨域请求

axios 默认是不能进行跨域请求的,而且也没法携带cookie,在vue中需要进行如下配置:

axios.defaults.withCredentials = true;

axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

axios.defaults.crossDomain = true;

然后后端也要进行跨域的设置,比如使用@Crossorigin注解,但是需要注意的是允许访问的域名不能使用通配符*,否则会失效。下面给出后端配置的代码样例:

@CrossOrigin(origins= {"http://www.mycart.com"}, allowCredentials = "true")

public class ItemController {

......

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值