这次给大家带来vue怎么进行ajax请求公共方法,vue进行ajax请求公共方法的注意事项有哪些,下面就是实战案例,一起来看一下。
为了减少代码的冗余,小编给大家推荐一篇介绍了决定抽离出请求ajax的公共方法的文章,供大家参考。
我使用了es6语法,编写了这个方法。
/**
* @param type 请求类型,分为post/get
* @param url 请求url
* @param contenttype
* @param headers
* @param data
* @returns {promise<any>}
*/
ajaxdata: function (type, url, contenttype, headers, data) {
return new promise(function(resolve) {
$.ajax({
type: type,
url: url,
data: data,
timeout: 30000, //超时时间:10秒
headers: headers,
success: function(data) {
resolve(data);
},
error: function(xmlhttprequest, textstatus, errorthrown) {
resolve(xmlhttprequest);
}
});
});
}
通过回调函数的方式返回请求结果。
测试代码如下:
getajaxdatamethod: function () {
const url = ;
const type = post;
const contenttype = application/json;
const headers = {};
const data = {};
api.ajaxdata(type, url, contenttype, headers, data).then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
})
}
测试通过!
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
angular17里的自定义指令使用详解
js里eventloop的使用详解
vue+cli单页面脚手架转换多页面脚手架的方法
以上就是vue怎么进行ajax请求公共方法的详细内容。