【问题标题】:XMLHttpRequest inside `onbeforeunload` handler not working in Opera`onbeforeunload` 处理程序中的 XMLHttpRequest 在 Opera 中不起作用
【发布时间】:2013-08-04 01:56:37
【问题描述】:

我有这样的脚本:

<script language="JavaScript" type="text/javascript">

    function enter() {
        this.chrono = new Date().getMilliseconds();
    }

    function leave() {
        this.chrono = new Date().getMilliseconds() - this.chrono;

        alert("test" + this.chrono);

            var blockingRequest = new XMLHttpRequest();
            blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + this.chrono, false); // async = false
            blockingRequest.send();

        return null;
    }

    window.onload = enter;
    window.onbeforeunload = leave;
</script>

PHP 部分(visitor_log/ajax_store_visit_duration.php 文件):

<?php

if(isset($_GET["visit_duration"]))
{
    $text = $_GET["visit_duration"];

    logtxt($text);

    echo "OK";
}
else die("application error");

function logtxt($text)
{
    $myFile = "test.txt";
    $fh = fopen($myFile, 'wb');
    fwrite($fh, $text);
    fclose($fh);
}

?>

它在 Chrome 中完美运行,但在 Opera 中无法运行。

如何让它跨浏览器?

【问题讨论】:

    标签: ajax cross-browser xmlhttprequest onbeforeunload


    【解决方案1】:

    它不应该在任何地方工作。 getMilliseconds() 返回日期对象的毫秒部分,而不是一些最终的毫秒值。该值始终低于 1000。在比较您的大小时没有用处。你真正想要的是世界时。

    (new Date()).valueOf() 应该为您提供可以使用的值。

    这可能是部分答案,因为您实际上并没有指定什么不起作用。

    【讨论】:

    猜你喜欢
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多