当浏览器或浏览器选项卡关闭时,从jQuery调用PHP

时间:2017-05-04 10:54:11

标签: javascript php jquery

以下是jquery代码,在关闭标签页或浏览器窗口之前显示警告:

$(window).on('beforeunload', function(){
    if(leave_window == false){
        debugger;
        var i =1;
        i++;
        alert('123'+i);
        return 'Are you sure you want to leave?';
    }  
});

我有一个php函数sendMail(),我想从这个代码块调用,但我很难这样做。如何在浏览器关闭之前调用php函数?

1 个答案:

答案 0 :(得分:-1)

$(window).on('beforeunload', function(){
    if(leave_window == false){
        debugger;
        var i =1;
        i++;


var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){

    }
});

 alert('123'+i);
        return 'Mail sent Successfully.. Are you sure you want to leave?';
    }  
});

在email.php中

<?php
if($_POST){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("example@gmail.com", "51 Deep comment from" .$email, $message);
}
?>

试试这个.. 我想,它会为你的pblm提供更好的解决方案