做前端开发的小伙伴们,和服务器端做数据交互一定是经常发生的事情。突然接到这样一个需求,可能会让一大部分处于初期阶段的鞋童们感到很无解。今天就原生的ajax请求和axios请求的中断方式分别贴出来,以备后用!
1、原生 XMLHttpRequest 方法中断操作;
function fetchData () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.snrthn.com/api/message', true);
xhr.send();
fetchData.stop = function () {
xhr.abort();
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
console.log(xhr.responseText);
}
}
}2、工具 Axios 方法中断操作;
function fetchData () {
axios.get('https://www.snrthn.com/api/message', {
cancelToken: new axios.CancelToken(function (cancel) {
fetchData.stop = function () {
cancel();
}
})
})
.then(function (res) {
console.log(res.data);
})
.catch(function (err) {
console.log(err);
});
}注:在此为了方便测试,故将服务器返回时间延迟了5秒。只需要调用 fetchData 方法即可中断当前请求。

发表评论