普通的ajax很少会涉及到需要取消请求的操作,但是在定时(setInterval)发送异步请求的时候,或者频繁切换数据时候,取消ajax就变得额外重要,这时候就需要取消之前未完成的请求.
1.jquery取消异步请求
var xhr;
var ajax = function () {
if (xhr && xhr.readyState != 4) {
xhr.abort();
}
xhr = $.ajax({
url: 'http://localhost:3123/jwApi/Report/jwQgReportController.do/_newXqmxData',
success: function (data) {
//do something
}
});
};
//轮询请求,,如果上一次请求未完成,则取消上次请求
setInterval(ajax, 2000);
2.axios取消异步请求
同时发送两次请求,取消其中一个
如果同时取消,可以使用同一个source.token
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<button id="a">停止</button>
<script type="text/javascript">
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get("http://localhost:3123/jwApi/Report/jwQgReportController.do/_newXqmxData", {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
//取消操作
console.log('Request canceled', thrown.message);
} else {
//处理异常
}
});
var source2 = CancelToken.source();
axios.get("http://localhost:3123/jwApi/Report/jwQgReportController.do/_newXqmxData", {
cancelToken: source2.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
//取消操作
console.log('Request canceled', thrown.message);
} else {
//处理异常
}
});
$('#a').click(function(){
source.cancel('Operation canceled by the user.');
})
</script>
</body>
</html>