我无法使用axios从api取消请求。我想做的是检查api是否获取数据,但是取消选中复选框后我无法取消。
axios文档正在显示此方法,但是它不起作用。
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
这是我的代码。
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
$(".customers-list").on("change", ":checkbox", function () {
let cusChecked = $(this);
let cusId = $(this).attr("id").slice(4);
let lat = $(this).attr("data-lat");
let long = $(this).attr("data-long");
let shoptype = $(this).attr("data-shoptype");
let products = $(this).parent().parent().attr("data-customerproducts");
if (cusChecked.is(":checked")) {
$(this).parent("p").parent("li").addClass("pending");
axios
.all([
axios.get(
`http://localhost/pharmevo_api/api.php?action=customerSale&idProduct=${products}&idshop=${cusId}&startdate='${timePeriodStart}'&enddate='${timePeriodEnd}'`
),
axios.get(
`http://localhost/pharmevo_api/api.php?action=customerSale&idProduct=${products}&idshop=${cusId}&startdate='${startDateTrend}'&enddate='${endDateTrend}'`
),{
cancelToken: source.token
}
])
.then((res) => {
console.log(res[0].data);
console.log(res[1].data);
})
.catch((error) => {
console.log(error);
});
} else {
source.cancel('Operation canceled by the user.');
}
});
如您所见,在其他情况下,如果未选中此复选框,则我正在取消请求