我一直试图在用户试图退出页面时发送电子邮件,我在jQuery中使用了beforeunload
事件。
jQuery代码:
$(window).on("beforeunload", function(e) {
console.log('posting');
$.post("file.php", {
d: logData,
s: 'New User Activity',
t: '[email protected]',
r: 'From: [email protected]\r\n',
},
function(data, status) {
console.log(data);
);
});
这段代码总是成功记录来自file.php
的响应,除非我使用mail()函数,顺便说一句,它只是在mail()函数后没有console.log
。
<?php
$fo = fopen("file.txt","a");
fwrite($fo,"Contents:\n".$_POST['d']."\nSubject: ".$_POST['s']."\nTo:".$_POST['t']);
fclose($fo); // THIS WORKS SUCCESSFULLY
mail("[email protected]","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
?>
基本上,beforeunload
中的任何异步都可能无法执行,具体取决于浏览器实际卸载页面的时间。
通过将async: false
传递给您的调用(docs here),尝试在您的情况下使用同步请求。