Ajax:如何防止jQuery在执行xmlHttpRequest.abort()之后调用成功事件. [英] Ajax: How to prevent jQuery from calling the success event after executing xmlHttpRequest.abort();

查看:275
本文介绍了Ajax:如何防止jQuery在执行xmlHttpRequest.abort()之后调用成功事件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery的$ .ajax()函数.无论哪里有意中止该请求,或者如果服务器关闭(不响应),都将发生相同的结果;

Using jQuery's $.ajax() function. Wherether the request has been purposely aborted, or if the server is down (not responding) it appears the same outcome happens;

这是在 xmlHttpRequest.status = 0 xmlHttpRequest.readyState = 4 的情况下触发的成功"处理程序.

That is the "success" handler gets triggered where xmlHttpRequest.status = 0 and xmlHttpRequest.readyState = 4.

(我通过关闭IIS,然后对已关闭"的网站执行xmlHttpRequest来模拟失败的请求)

(I simulated the failed request by shutting off IIS, and then executing a xmlHttpRequest against the website that had been "turned off")

所以我的问题是我如何确定中止的请求或由于服务器未响应(因为服务器可能已关闭)而导致真正失败的请求之间的区别,因为这两种情况似乎都给我相同的状态/readyState?

So my question is how can I determine the difference between an aborted request, or a request that genuinely failed due to the server not responding (because maybe the server is down), since both scenarios appear to give me the same status/readyState?

编辑 更准确地说,我想知道在ajax上调用.abort()函数之后,如何防止调用成功"处理程序.

EDIT More accurately I want to know how to prevent calling the "success" handler after the .abort() function is called on ajax.

我重新措词以反映这一点.

I have re-worded the question to reflect this.

推荐答案

jQuery< 1.5

对于jQuery< 1.5我想出了以下解决方案:

jQuery < 1.5

For jQuery < 1.5 I have come up with the following solution:

var request = $.ajax( /* ... */ );

// ...

request.onreadystatechange = function () {};
request.abort();

所以,基本上,我要做的是在调用abort()之前删除回调处理程序.

So, basically what I do, is to remove the success callback handler before calling abort().

这就像一种魅力.

从jQuery 1.5开始,$.ajax(), $.get(), …函数返回jXHR对象( api文档),而不是xmlHttpRequest对象.因此,您不能简单地覆盖xmlHttpRequest.onreadystatechange()处理程序.

Starting with jQuery 1.5 the $.ajax(), $.get(), … functions return the jXHR object (api documentation) instead of the xmlHttpRequest object. Hence you can not simply overwrite the xmlHttpRequest.onreadystatechange() handler.

这就是说,jXHR.abort()负责不调用success回调处理程序.因此,调用jXHR.abort()就足够了.

This said, the jXHR.abort() takes care of not calling the success callback handler. Hence it is sufficient to call jXHR.abort().

您不必更新以前的代码,因为将onreadystatechange设置为jXHR根本没有任何作用.

You do necessarily not need to update your previous code, as setting an onreadystatechange to jXHR will just have no effect at all.

长话短说,从 jQuery 1.5 开始,这可以做到:

Long story short, startin with jQuery 1.5, this will do:

var jxhr = $.ajax( /* ... */ );

// ...

jxhr.abort();

这篇关于Ajax:如何防止jQuery在执行xmlHttpRequest.abort()之后调用成功事件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆