普通的ajax很少會(huì)涉及到需要取消請求的操作拢军,但是在定時(shí)(setInterval)發(fā)送異步請求的時(shí)候,或者頻繁切換數(shù)據(jù)時(shí)候屯吊,取消ajax就變得額外重要,這時(shí)候就需要取消之前未完成的請求.
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取消異步請求
同時(shí)發(fā)送兩次請求,取消其中一個(gè)
如果同時(shí)取消,可以使用同一個(gè)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>