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

标签 javascript php jquery ajax

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

如果他点击 Leave this page -> 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;
}

最佳答案

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

为了执行一段代码(这不仅适用于AJAX) 只有当用户点击Stay 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;
}

如果用户点击离开此页面,如何运行代码

如果用户选择离开页面,页面就会开始卸载,当它完全卸载时 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
});

});

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

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

ajax-call.php 只包含

echo $_POST["chosenOpt"] . "_" . rand(1, 9999);

离开此页面时输出为leave_[number]留在此页面时为stay_[number]

注意:您可以看到 leave_[number]刷新页面并且如果选中Preserve Log在控制台中。

关于Javascript - 检测用户点击导航弹出窗口的选项的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29740464/

相关文章:

javascript - 如何使用 Angular js在两个 Controller 之间传递范围?

php - 多选进入输入框

php - 元标记未显示在使用 jquery 添加的页面 View 源中

javascript - 单击链接两次(而不是一次)时会激活灯箱

javascript - 我如何使这个轮播实现更好?

jQuery 选择选项列表在 IE6 中更新得不够快

javascript - 在 jquery 中访问 angular2 变量

javascript - 通过js输出css grid和普通grid不一样?

php - 允许用户管理大量数据库行的最佳方式

javascript - 每隔给定时间 self 刷新数据库