我有一个进行ajax调用的类
export default class AjaxCall {
constructor(options) {
// some options
}
ajax(options) {
return new Promise((resolve, reject) => {
$.ajax(options).done(resolve).fail(reject);
});
}
doAjax() {
return this.ajax({
type: 'GET',
...
}
}
我在另一个文件中调用这个ajax
import AjaxCall from './ajax';
$(function() {
const options = {...};
const ajaxCall = new AjaxCall(options);
$('.button-start').on('click', function() {
ajaxCall.doAjax(options ...);
});
});
所以我想知道是否可以有一个方法(或其他方式)来停止该 ajax 调用,这样我就可以有另一个按钮在单击时调用此方法。
我知道有 xhr.abort()
但当 xhr
是设置为 ajax 调用的变量时会使用它。
最佳答案
我会简单地返回 jqXHR
对象,而不是将其包装在 Promise
中。
ajax(options) {
return $.ajax(options);
};
这样,您就可以访问abort
方法,例如
let jqXHR = ajaxCall.doAjax(options ...)
if (someAbortReason) {
jqXHR.abort()
}
仅供引用...
The jqXHR objects returned by
$.ajax()
as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).
然而,需要注意的一件重要事情是 jQuery 只添加了 catch
v3.0 中的 Deferred 对象 API 的方法
关于javascript - 停止从方法调用的 ajax 请求 (ES6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47025255/