在onbeforeunload中使用Ajax自动保存字段数据

Using Ajax in onbeforeunload to autosave field data

本文关键字:保存 字段 数据 Ajax onbeforeunload      更新时间:2023-09-26

我试图在窗口中使用AJAX。Onbeforeunload功能自动保存在我的网站页面上的文本字段(没有保存按钮,它都是在后台完成的)。保存函数是用PHP编写的。我开始尝试如下:

window.onbeforeunload = function(e){
  var noteelement = document.getElementById( 'note' );
  var mynote = noteelement.value;
  $.post('save_my_note.php', { thenote: mynote }, function(data){});
  };

在研究中,我已经明白,由于ajax调用的异步性质,php代码不会被调用,因为窗口在函数从服务器触发之前关闭。

当然,正如其他人所说,如果我在onbeforeunload函数中添加返回值以导致对话框弹出(这将是"您确定要离开"框),它确实工作,因为.post调用有时间运行,而对话框等待响应:

  $.post('save_my_note.php', { thenote: mynote }, function(data){});
  return mynote;
  };

有人说我必须把这个post调用改为异步AJAX,以便函数等待函数完成,但不是非常精通语法,我不太确定我需要的语法。我尝试了以下命令来代替post函数:

        $.ajax({
            url: "save_my_note.php",
            data: "{thenote: mynote}",
            async: false                 
        });

然而,这似乎也不起作用。

是否有人有一个简单的代码示例,通过onbeforeunload(或onunload??)函数实现同步方式的自动保存?我不是javascript或jquery专家,我在网上找到的例子令人困惑。

你的最后一个例子应该工作,你需要改变asynch: falseasync: false(额外的h必须删除)根据jQuery文档

也许你可以强制超时暂停-不知道这是否实际工作,只是一个猜测:

var bSaved = false;
window.onbeforeunload = function(e){
  bSaved = false;
  var noteelement = document.getElementById( 'note' );
  var mynote = noteelement.value;
  $.post('save_my_note.php', { thenote: mynote }, function(data){ bSaved = true; });
  window.setTimeout('bSaved = true',2000);
  while (!bSaved) {}
  };