【问题标题】:onbeforeunload wait for ajax resultonbeforeunload 等待ajax结果
【发布时间】:2011-03-15 10:30:22
【问题描述】:

onbeforeunload() 函数是否可以等待 ajax 结果并根据结果值移动到 jsp 或至少在卸载之前显示一条消息?

是否可以使用 setTimeOut 或一些自定义等待功能来解决这个问题,或者我必须考虑其他一些工作流程

【问题讨论】:

  • 也许是同步调用

标签: javascript jquery ajax


【解决方案1】:

使用a synchronous XmlHttpRequest call(“AJAX”是一个误称)。

【讨论】:

    【解决方案2】:

    AFAIK,这是不可能的。 onbeforeunload 的功能非常有限,否则恶意网站可能会阻止您离开他们的网站。

    附录:可能会显示“您将离开此页面”之类的消息。在这种情况下,beforeunload() 函数必须返回一个字符串。

    例子

    window.onbeforeunload = function() {
       return 'Are you sure about that?';
    }
    

    【讨论】:

    • 实际上该消息包含 ajax 结果的一些内容。无论如何我认为这个工作流程不好,我将使用 redirectAction 并使用其他技巧显示消息
    【解决方案3】:

    显示警告框等待来自 ajax 的响应不是一个好主意。一般你可以在ajax响应后使用alert box来确认离开页面。

    例如,为了避免使用警报,您可以同步调用 Ajax

    if(window.XMLHttpRequest) xmlHttpObj=new XMLHttpRequest();
    else xmlHttpObj=new ActiveXObject("Microsoft.XMLHTTP");
    if(xmlHttpObj){
    xmlHttpObj.onreadystatechange=function(){
    if(xmlHttpObj.readyState==4 && xmlHttpObj.status == 200){
     // your logic required
    }
    }
    xmlHttpObj.open("GET", "your request url", false); // used false for synchronous call 
    xmlHttpObj.send(null);
    }
    else{
    alert("AJAX not support");
    }    
    

    【讨论】:

      【解决方案4】:

      这是我的策略,适合我:

      _number_of_active_ajax ++;
      $.ajax({
          url: REQUEST_URL,
          timeout: 3000
      })
      .always(function() {
          _number_of_active_ajax --;
      });
      
      window.onbeforeunload = function() {
          if(_number_of_active_debounce > 0 || _number_of_active_ajax > 0)
              return "Your question";
      }
      

      }

      如果页面有活动请求,它将显示一条消息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 2013-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-30
        • 2017-04-26
        相关资源
        最近更新 更多