【问题标题】:jQuery unload doesn't work in ChromejQuery 卸载在 Chrome 中不起作用
【发布时间】:2015-10-01 20:44:54
【问题描述】:

我编写了一个 Web 方法,它将在 jQuery 的卸载事件中调用。当我通过 Visual Studio 运行时,它正在运行。我部署在 IIS 中。当我在 IE 和 Firefox 中执行应用程序时,它也可以工作。当我在 Chrome 中运行该应用程序时,它奇怪地没有触发卸载事件。以下是我写的:

  <script type="text/javascript" language="javascript">
    var startTime;

    $(window).load(function () {
        startTime = new Date().getTime();
    });

    $(window).unload(function () {
        var endTime = new Date().getTime();
        var diff = new Date(endTime - startTime);
        var path = window.location.pathname.toString();

            $.ajax({
                type: "POST",
                url: path + "/LogUserActivity",
                data: "{ 'timeSpent': '" + Math.floor(diff / 1000).toString() + "', 'urlVisited': '" + path + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                },
                error: function (xhr, status, error) {
                },
                failure: function () {
                }
            });
    });

</script>

【问题讨论】:

  • 有很多类似的问题。做一些谷歌搜索,看看你找到了什么。
  • ajax 不能保证在卸载时触发。您可以尝试将其设为同步请求。
  • @DLeh:我已经尝试过了,并且花了很多时间研究,但找不到任何线索。
  • 我认为这是一个重复的问题,请检查:stackoverflow.com/questions/2274949/…
  • 我正在尝试测试@DanielA.White 的解决方案。

标签: javascript jquery asp.net google-chrome


【解决方案1】:

感谢@Daniel A. White

这不是 jQuery 卸载的问题,而是 AJAX 同步调用的问题。

使我的 AJAX 调用同步而不是异步,这在 Chrome 以及所有其他浏览器上都有效。

 $.ajax({
                async: false,
                type: "POST",
                url: path + "/LogUserActivity",
                data: "{ 'timeSpent': '" + Math.floor(diff / 1000).toString() + "', 'urlVisited': '" + path + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                },
                error: function (xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                },
                failure: function () {
                }
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-06
    • 2011-02-28
    • 2013-03-18
    • 2011-11-19
    • 2017-09-05
    • 2011-03-07
    • 2019-01-29
    • 2013-08-08
    相关资源
    最近更新 更多