Send AJAX to server beforeunload [duplicate]

ⅰ亾dé卋堺 提交于 2019-11-26 14:30:02

问题


So supposedly starting at Firefox > 4, binding the window jQuery object to beforeunload doesn't work anymore.

What'd I'd like to do is submit an AJAX post to delete my server's memcache data.

When I refresh the only open tab, I can see that the beforeunload event is called in both firefox and chrome with the following code as evidenced by the console.log message, "firefox/NON-firefox delete". The problem is that I never see the console.log message "memcache delete" indicating that my server never saw the $.ajax request.

I realize it is bad to do browser sniffing and that there is no difference between what's included in the if and else statements. I'm merely showing code for what I've tried unsuccessfully in Firefox.

Anyone have any ideas?

$(window).bind('beforeunload', function(){ 
  if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
    console.log('firefox delete');
     memcacheDelete();
     return null;
  } 
  else {
    console.log('NON-firefox delete');
    memcacheDelete();
    return null;
  }
});

function memcacheDelete() {
   $.ajax({
      url: "/memcache/delete", 
      type: "post",
      data:{}, 
      success:function(){
          console.log('memcache deleted');
      }//success
  }); //ajax
}

回答1:


Ajax is asynchronous.

When you refresh (or close)your browser, beforeunload is being called. And it means as soon as beforeunload is finished executing, page will refresh (or close).

When you do an ajax request, (since its asynchronous) javascript interpreter does not wait for ajax success event to be executed and moves down finishing the execution of beforeunload.

success of ajax is supposed to be called after few secs, but you dont see it as page has been refreshed / closed.

Side note:

.success() method is deprecated and is replaced by the .done() method

Reference




回答2:


Just for sake of completion, here's what I did, thanks to @Jashwant for the guidance: I noticed that this other SO Q&A suggested the same solution. The KEY is the async:true(false) in the $.ajax call below:

$(window).bind('beforeunload', function(){ 
  if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
    console.log('firefox delete');
     var data={async:false};
     memcacheDelete(data);
     return null;
  } 
  else {
    console.log('NON-firefox delete');
     var data={async:true};
     memcacheDelete(data);
    return null;
  }
});

function memcacheDelete(data) {
  $.ajax({
    url: "/memcache/delete", 
    type: "post",
    data:{}, 
    async:data.async,
    success:function(){
      console.log('memcache deleted');
    }//success
  }); //ajax
}


来源:https://stackoverflow.com/questions/14929832/send-ajax-to-server-beforeunload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!