在$就回调,我怎么区分用户导航走不可达的服务器?可达、回调、服务器、我怎么

由网友(油炸小可爱)分享简介:情况:您已经获得了一些$就请求仍在运行的服务器。他们所有的错误用xhr.status === 0和xhr.readyState === 0。You've got a few $.ajax requests to the server that are still running. They all error o...

情况:

您已经获得了一些$就请求仍在运行的服务器。他们所有的错误用xhr.status === 0和xhr.readyState === 0。

You've got a few $.ajax requests to the server that are still running. They all error out with xhr.status === 0 and xhr.readyState === 0.

可能的原因:

在服务器已关闭(编辑:作为可达 - 无头返回或任何东西)。 在用户点击一个链接/刷新页面/否则导航离开。

我想弹出一个对话框,在第一种情况下,却忽略了第二位。我如何在这两者之间在我的完整方法区分?完整的方法激发的$(窗口).unload事件之前,所以我不能用它来确定用户是否点击了。我还可以使用一个setTimeout的尝试等待下一个页面加载,但是这是肮脏的。有没有别的东西,我可以做什么?

I would like to pop up a dialog in the first case, but ignore the second. How do I distinguish between these two in my complete method? The complete method is fired before the $(window).unload event, so I can't use that to determine if the user clicked away. I could also use a setTimeout to try to wait for the next page to load, but that's dirty. Is there something else I can do?

推荐答案

(这个答案是另一个答案的抽象,为了清晰起见由OP的要求) 如果窗口级别标志不工作,接下来的DOM级事件之前 $(窗口).unload window.onbeforeunload 。那是一个可行的选择?

(This answer is an abstract of another answer, for clarity's sake by the OP's request) If a window level flag isn't working, the next dom level event to test before $(window).unload is window.onbeforeunload. Is that a viable option?

在你的AJAX方法:

var running = true;
// do this only once!!!
var _obunload = ( window.onbeforeunload )? window.onbeforeunload: function(){};
window.onbeforeunload = function() 
{ 
     _obunload.call( window );
     running = false;
}
xhr.onreadystatechange = function()
{
    if( !xhr.status && !xhr.readyState && running )
    {
        // warning! warning! danger Will Robinson!
        // there was a server error
    }
    else if( !xhr.status && !xhr.readyState )
    {
        // user did something... Who gives?
    }
    running = false;
}