【问题标题】:How to use .ashx file to execute some codes when a user closes a webpage当用户关闭网页时如何使用 .ashx 文件执行一些代码
【发布时间】:2015-01-02 13:42:52
【问题描述】:

我想在用户关闭网页时执行一些 vb.net 代码。我该怎么办。我有这个但我不知道如何使用它。我在某处看到了下面的说明但我无法使用它:

您可以将 ajax 调用绑定到“beforeunload”页面 html 事件。只需确保使用 async false 调用 ajax,否则页面将在删除行的代码实际运行之前关闭。我假设您使用 jQuery 进行 ajax 调用。

例如在html中:

<body onbeforeunload="runCode();">

你的 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>

名为 YourCode.ashx 的文件将包含删除您的数据库行的代码,或者您想要完成的任何其他操作。这样,即使用户关闭浏览器,代码也会运行。请注意,如果 YourCode.ashx 中的代码有问题,异步 false 调用可能会锁定您的页面。

【问题讨论】:

  • 那么您面临的问题在哪里?
  • 我对 .ashx 不太熟悉。例如,如何在关闭页面之前使用此方法显示消息?我想在 .ashx 文件上实现这段代码:MsgBox("hi") 你也可以看到这个页面:[stackoverflow.com/questions/27739233/…
  • 出现错误提示:Microsoft JScript runtime error: '$' is undefined

标签: jquery html asp.net vb.net ashx


【解决方案1】:

由于您使用的是 jQuery,因此您可以使用unload event。确保包含 jQuery。

仅供参考:如果您使用 jQuery 卸载事件,请从 body 标记中删除 onbeforeunload="runCode();"

<body>
    <form id="form1" runat="server">
        This is content.

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
        </script>
        <script type="text/javascript">
            $(window).unload(function () {
                $.ajax({
                    url: 'YourCode.ashx',
                    async: false,
                    success: function (data) {
                        // Do other things before navigating 
                        // to other page or closing the browser
                    }
                });
            });
        </script>
    </form>
</body>

【讨论】:

  • 我不使用jquery,我应该使用什么?
  • @user3724490 $.ajax 是jQuery.ajax()。你正在使用 jQuery (虽然你不知道),但是你没有包含 jQuery Script。这就是您收到 Microsoft JScript runtime error: '$' is undefined 错误的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-04
  • 2018-04-26
相关资源
最近更新 更多