1

我正在尝试在 window.onbeforeunload 函数中使用 AJAX 来自动保存我网站页面上的文本字段(没有保存按钮,这一切都在后台完成)。保存功能是用 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 专家,我在网上找到的示例令人困惑。

4

2 回答 2

2

您的最后一个示例应该可以工作,您需要根据 jQuery 文档更改asynch: false为(必须删除async: false额外的h )

于 2012-01-03T21:52:25.307 回答
0

也许你可以强制暂停 - 不知道这是否真的有效,只是猜测:

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) {}

  };
于 2012-01-03T21:48:52.873 回答