在 beforeunload/unload 上发送 Ajax 调用

Awa*_*mar 3 javascript php ajax jquery date

场景:我正在创建一个事件注册模块,用户可以在其中从日历中选择一个日期进行预订,填写一些输入字段并支付预订日期。其中一项要求是,每个日期只能进行一次预订。这出现了两个人想要在同一时间预订相同日期的情况。因此,我们需要向稍后来预订该日期的用户显示一条消息,表明该特定日期的预订已经在进行中。请稍后再回来查看

为此,每当用户选择日期时,我都会在我的数据库中创建一个临时条目。针对该条目,我可以向后来来的其他用户显示该消息。

从逻辑上讲,如果第一个用户,则必须删除该条目:

  1. 选择其他日期。
  2. 关闭他的浏览器或离开页面

以便它可供想要预订同一日期的第二个用户使用。

问题:一旦用户更改了他选择的日期,我就可以删除该条目。我无法实现第二个。我编写了一个函数,该函数将删除该行并在 onbeforeunload jQuery 事件上调用该函数。显然,该函数不适用于 jQuery。

window.onbeforeunload = function(){
  deleteTempEntry(); //This sends an ajax call to delete the entry. Not working.

  alert("The second alert"); // even this alert doesn't work.

  // I actually intend to use confirm box to make sure to not to delete the entry if the user does not leave the page.
  confirm("Your current progress will be removed. Are you sure?"); 

  //Calling this return function shows the warning message but none of the other code works.
  //return 'Are you sure you want to leave?';
};
Run Code Online (Sandbox Code Playgroud)

我试过,bind/on/pure JS,但这些似乎都不起作用。

正如这里所解释的,由于安全原因,我对 onbeforeunload/unload 事件无能为力。有什么解决方法吗?

谢谢。

Vla*_*rev 10

我需要这样的东西。但不幸的是,在 onBeforenUnload 中调用后端并不可靠。大多数 AJAX 调用不会到达后端(有些可能);唯一有保证的调用是使用navigator.sendBeacon(url, data)。即使浏览器关闭,它也会发送 POST 请求。