在$就回调,我怎么区分用户导航走不可达的服务器? [英] In a $.ajax callback, how do I distinguish an unreachable server from a user navigating away?

查看:145
本文介绍了在$就回调,我怎么区分用户导航走不可达的服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:

您已经获得了一些$就请求仍在运行的服务器。他们所有的错误用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;
}

这篇关于在$就回调,我怎么区分用户导航走不可达的服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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