Beforeunload功能不起作用并且在卸载后不更新记录

时间:2017-08-31 05:51:59

标签: php ajax onbeforeunload onunload

这是我的代码

function myfoo() {
  $.ajax({
    type: "POST",
    url: "update.php",
    dataType: 'json',
    async: false,
    data: {
      Eventid: 1,
      Seats: 'Seats'
    },
    success: function(r) {}
  });
}

$(window).on('beforeunload', function() {
  return 'Are you sure you want to leave?';
});
$(window).on('unload', function() {
  console.log('calling ajax');
  myfoo();
});

update.php代码

<?php
session_start();
include 'conn.php';

if(isset($_SESSION['Seats'])) {
    $seatS=$_SESSION['Seats'];
    $Eventid=$_SESSION['Eventid'];
    $cats = explode(" ", $seatS);
    $cats = preg_split('/,/', $seatS, -1, PREG_SPLIT_NO_EMPTY);
    foreach($cats as $key => $cat ) {
        $cat  = mysql_real_escape_string($cats[$key]);
        $cat = trim($cat);
        if($cat !=NULL) {
            $stmt = $con->prepare('UPDATE fistevent SET `Status`=" " where `Event_Id`=? AND `seats`="'.$cat.'" AND `Status`="Hold" ');
            $stmt->bind_param("s", $_SESSION['Eventid']);
            $stmt->execute();
            session_destroy();
        }
    }
}

?>

1 个答案:

答案 0 :(得分:1)

AJAX data:参数放在$_POST中,而不是$_SESSION

如果您使用mysql_real_escape_string,则无法使用mysqli。使用bind_param()时无需转义参数。并且您可以使用explode()代替preg_split(),因为分隔符中没有正则表达式模式; array_filter()可用于删除空白条目。

<?php
include 'conn.php';

if(isset($_POST['Seats'])) {
    $seatS=$_POST['Seats'];
    $_SESSION['Seats'] = $seatS;
    $Eventid=$_POST['Eventid'];
    $_SESSION['Eventid'] = $Eventid;
    $cats = array_filter(array_map('trim', explode(',', $seatS)));
    $stmt = $con->prepare('UPDATE fistevent SET `Status`=" " where `Event_Id`=? AND `seats`= ? AND `Status`="Hold" ') or die($con->error);
    $stmt->bind_param("ss", $_POST['Eventid'], $cat);
    foreach($cats as $key => $cat ) {
        $stmt->execute();
    }
}
?>