我已经定义了一个像这样发送 jquery ajax 请求的方法
sendAjaxRequest(URL, data) {
return $.ajax({
type : 'POST',
url : URL,
crossDomain : true,
data : JSON.stringify(data),
dataType : 'json'
}).fail((responseData) => {
if (responseData.responseCode) {
console.error(responseData.responseCode);
}
});
}
从调用的地方我保留了ajax调用的引用
this.ajaxRequest = sendAjaxRequest(Url, data);
如果用户离开页面(通过路由器转到同一网站上的另一个页面),则基于用户导航我想取消任何待处理的 ajax 请求。
从文档中我发现 jquery jqXHR
对象有一个 abort
方法来取消任何 ajax 请求。但是在我的 ajaxRequest
对象中我没有任何这样的方法可用。我正在使用 jquery 2.2。
为了澄清,我还想补充一点,我正在使用 react,并希望实现这一目标。
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
取自此link .
他们基本上说异步获取数据时,在卸载组件之前使用 componentWillUnmount 取消任何未完成的请求。
我一定是做错了什么。感谢您的帮助。
最佳答案
根据ajax documentation ,你做得对。 $.ajax()
函数返回一个具有abort
函数的对象。您应该检查该函数是否存在,因为如果请求已经完成,它可能不存在。
componentWillUnmount: function(){
if (this.ajaxRequest && this.ajaxRequest.abort){
this.ajaxRequest.abort()
}
}
关于javascript - 当用户导航到其他页面时如何中止挂起的 jquery ajax 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314408/