在卸载之前发送Ajax呼叫 [英] Send an Ajax Call on beforeunload/unload

查看:48
本文介绍了在卸载之前发送Ajax呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Scenario: I am creating an event registration module in which a user would choose a date from a calendar for booking, fill some input fields and pay up to book the date. One of the requirements is that, there can be only one booking per date. This arises a case where two people want to book the same date on the same time. So, we need to show the user who came later to book the date a message that a booking is already in progress for that specific date. Please check back later.

要实现此目的,每当用户选择日期时,我都会在数据库中创建一个临时条目.对于该条目,我可以将消息显示给以后再来的其他用户.

For this to achieve, I am creating a temporary entry in my DB whenever a user chooses a date. Against that entry, I can show the message to the other user who came later.

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

Logically, that entry has to be deleted if the first user:

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

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

So that it would be available for the second user who wants to book for the same date.

问题:一旦用户更改了所选日期,我便可以删除该条目.我无法达到第二个目标.我编写了一个函数,该函数将删除该行并在onbeforeunload jQuery事件中调用该函数.显然,该功能不适用于jQuery.

The Problem: I am able to delete the entry once a user changes his selected date. I am not able to achieve the second one. I wrote a function that will delete the row and calling that function onbeforeunload jQuery event. Apparently, that function is not working with 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?';
};

我尝试过,绑定/打开/纯JS,但是似乎都不起作用.

I tried, bind/on/pure JS but none of those seem to work.

此处中所述,由于安全原因,我对onbeforeunload/unload事件无能为力.有任何解决方法吗?

As explained here, there isn't really much I can do with onbeforeunload/unload events because of the security reasons. Any workaround for this?

谢谢.

推荐答案

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

I needed something like that. But unfortunately calling the backend in onBeforenUnload is not reliable. Most AJAX calls will not reach the backend (some may); The only guaranteed call is with navigator.sendBeacon(url, data). It sends POST request even the browser is closed.

这篇关于在卸载之前发送Ajax呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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