onbeforeunload wait for ajax result

前端 未结 4 1439
梦谈多话
梦谈多话 2021-01-23 15:32

Is it possible for onbeforeunload() function to wait for ajax result and move to a jsp based on the resultvalue or atleast show a message before unloading?

相关标签:
4条回答
  • 2021-01-23 15:59

    Use a synchronous XmlHttpRequest call ("AJAX" is a mis-nomer).

    0 讨论(0)
  • 2021-01-23 16:07

    It is not good Idea to display alert box for waiting response from ajax. Generally you can use alert box for message for confirmation of Leaving page after ajax response.

    For avoiding use of alert you can call Ajax synchronously for example

    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");
    }    
    
    0 讨论(0)
  • 2021-01-23 16:20

    This is my strategy and works for me:

    _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";
    }
    

    }

    It will show a message to use if the page has an active request.

    0 讨论(0)
  • 2021-01-23 16:25

    AFAIK, it is not possible. onbeforeunload has very limited functionality, otherwise malicious sites could stop you from leaving their site.

    Addendum: It is possible to show a message like 'You are leaving this page'. In that case, the beforeunload() function must return a string.

    Example

    window.onbeforeunload = function() {
       return 'Are you sure about that?';
    }
    
    0 讨论(0)
提交回复
热议问题