查询beforeunload事件的数据库

Query database on beforeunload event

本文关键字:数据库 事件 beforeunload 查询      更新时间:2023-09-26

我想知道是否有可能在beforeunload事件上向数据库发送查询。

$(window).on('beforeunload',function() {
    console.log('beforeunload called. run query');
});

如果有,我该怎么做?我需要运行一个查询来插入动态值到数据库中。

您可以尝试一下,但是要注意onbeforeunload事件对于某些浏览器是有限的。

window.onbeforeunload = mySession;
function mySession(){
    $.ajax({
        url: "/../../myPHP.php",
        async: false,
        type: "GET"
    });
    return "WhatEverMessageYouFeelLike";
}

和你的PHP执行查询从AJAX处理..

$delete = "DELETE FROM MyTable WHERE id=" .$_SESSION['mySessionVariable'];
// your query..

使用jQuery AJAX调用。假设你要发布你的数据,试试这个:

$.post(
    'your/url',
    {
        your : "Post Vars"
    },
    function(data) {
        // not sure if you'll need to do anything here actually.
    },
    'json' // or 'html', or whatever you want your return format to be
);

我认为jQuery使用post的最好方法是$.post()方法。但是你也可以使用$.ajax

使用示例:

jQuery

$.post( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
});
jQuery Ajax

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});