Execute some codes when closing an Asp.net page

吃可爱长大的小学妹 提交于 2019-12-25 07:00:44

问题


I want to delete a row in a Database table when a user closes an .aspx page. How could I do it? I know how to delete a row in a Database table but I don't know how to do it when a user leaves an .aspx page?


回答1:


You can bind an ajax call to the "beforeunload" page html event. Just make sure to call ajax with async false, otherwise the page will be close before the code to delete the row actually runs. I'm assuming you are using jQuery for the ajax call.

For example, in html:

<body onbeforeunload="runCode();">

YOUR HTML....

<script type="text/javascript">
function runCode() {
    $.ajax({
        url: 'YourCode.ashx',
        async: false,
        success: function(data) {
            //Do other things before navigating to other page or closing the browser
        }
    });
}
</script>
</body>

The file named YourCode.ashx will contain the code to delete your db row, or whatever else you want to be done. In this way the code will be run even if the user closes the browser. Just note that the async false call can lock your page if the code in YourCode.ashx has problems.



来源:https://stackoverflow.com/questions/27739233/execute-some-codes-when-closing-an-asp-net-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!