【问题标题】:JQuery 'beforeunload' event doesn't console.log the response from $.post to mail() in PHPJQuery 'beforeunload' 事件不会 console.log 从 $.post 到 PHP 中的 mail() 的响应
【发布时间】:2018-03-03 07:52:58
【问题描述】:

每当用户尝试退出页面时,我一直在尝试发送电子邮件,我在 jQuery 中使用了beforeunload 事件。

jQuery 代码:

 $(window).on("beforeunload", function(e) {
     console.log('posting');
     $.post("file.php", {
             d: logData,
             s: 'New User Activity',
             t: 'example@gmail.com',
             r: 'From: info@address.com\r\n',
      },
      function(data, status) {
        console.log(data);
      );
 });

除非我使用 mail() 函数,否则此代码始终成功记录来自 file.php 的响应,顺便说一句,它只是在 mail() 函数之后没有 console.log

file.php 内容:

<?php
$fo = fopen("file.txt","a");
fwrite($fo,"Contents:\n".$_POST['d']."\nSubject: ".$_POST['s']."\nTo:".$_POST['t']);
fclose($fo); // THIS WORKS SUCCESSFULLY

mail("example@domain.com","Subject","Msg"); //I changed this to static values so i check if the problem
//is coming from the POST, but still no success

echo "fine"; //THIS DOESN'T SHOW UP IN THE CONSOLE
?>

【问题讨论】:

  • this。您可能希望在您的情况下使用同步请求(请参阅 jQuery 文档中的 async: false)。
  • 谢谢@Jeto,这是解决方案,请在答案框中写下您的评论,以便我批准

标签: javascript php jquery email onbeforeunload


【解决方案1】:

this answer

基本上,beforeunload 中的任何异步操作都可能不会执行,具体取决于您的浏览器何时实际卸载页面。

在您的情况下尝试使用同步请求,将async: false 传递给您的调用 (docs here)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    相关资源
    最近更新 更多