Javascript - 检测用户点击导航弹出窗口的选项的方法

Abh*_*nav 5 javascript php ajax jquery

当用户关闭浏览器选项卡时,我想根据他单击的选项发出 ajax 请求。

如果他点击离开此页面 -> Ajax Call 1

如果他点击 Stay on this page -> Ajax Call 2

这是我的代码现在的样子

我想在用户选择任一选项后执行此 ajax 调用。但目前,如果用户尝试关闭选项卡,ajax 调用会自动运行

window.onbeforeunload = userConfirmation;

function userConfirmation(){
  var cookieName  = $.trim("<?php echo $this->uri->segment('5') ?>");
  var toValue     = $.trim($('#toValue').val());
  document.cookie = cookieName+'=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/';
  var confirmation = 'The message will be discarded.';
  $.ajax({
    type: 'POST',
    url: "<?php echo BASE_URL.'index.php/admin/mail_actions/deleteSessionDatas' ?>",
    data: {'toValue':toValue},
    dataType: 'html',
    success: function(response){
      console.log(response);
      var response = $.trim(response);
    }
  });
  return confirmation;
}
Run Code Online (Sandbox Code Playgroud)

Cli*_*ton 3

好吧,我提出这是一个黑客而不是解决方案,这只是一个解决方案。

为了仅在用户单击时执行一段代码(这不仅适用于AJAXStay on this page,您必须使其异步运行,从而javaScript保持运行同步代码(return语句)。

jQuery.ajax()调用必须包含该参数,然后用户单击async: true要执行的代码必须包含在具有适当超时的函数中(如果页面需要太多时间来卸载,则超时必须更高)setTimeout()

var stayHere = ""; // this variable helps with the "stay on this page"_code cancellation when user chooses "leave this page"
window.onbeforeunload = userConfirmation;

function userConfirmation() {
    var confirmation = "Your edits will be lost";
    stayHere = setTimeout(function() { // the timeout will be cleared on "leave this page" click
        $.ajax({
            url: "ajax-call.php",
            type: "post",
            data: {chosenOpt: "stay"},
            async: true, // important
            success: function(data) { console.log(data);},
            error: function() { alert("error");}
        });
    }, 2000); // Here you must put the proper time for your application
    return confirmation;
}
Run Code Online (Sandbox Code Playgroud)

如果用户点击,如何运行代码Leave this page

如果用户选择离开页面,则页面开始卸载,当它完全卸载时unload,事件会触发,所以我将代码放入其侦听器中:

jQuery(window).on("unload", function() {
clearTimeout(stayHere); // This is another assurance that the "stay here"_code is not executed
$.ajax({
    url: "ajax-call.php",
    type: "post",
    data: { chosenOpt: "leave"},
    async: false, // If set to "true" the code will not be executed
    success: function(data) { console.log(data);},
    error: function() { console.log("Error");} // In chrome, on unload, an alert will be blocked
});
Run Code Online (Sandbox Code Playgroud)

});

注意:请小心处理程序内执行的代码unload。由于该事件在所有内容都被卸载后unload触发,因此页面中没有任何对象仍然可用。

这是一个jsfiddle来看看它是如何工作的。

其中ajax-call.php仅包含

echo $_POST["chosenOpt"] . "_" . rand(1, 9999);
Run Code Online (Sandbox Code Playgroud)

并且输出会一直leave_[number]持续Leave this page下去stay_[number]Stay on this page

注意:leave_[number]您只能看到刷新页面以及控制台中是否选中“保留日志” 。

  • 嗨@IdentityUnkn0wn,我添加了一个 [jsfiddle](https://jsfiddle.net/j96mbedh/4/) 来向您展示它是如何工作的,但它没有“AJAX”。我希望这会有所帮助。 (4认同)