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

查看:15
本文介绍了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 = 0xmlHttpRequest.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")

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

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() 之前删除 success 回调处理程序.

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天全站免登陆