AJAX的简单访问持续时间记录器


Simple visit duration logger with AJAX

我在记录访问持续时间时遇到问题。

我写了这样的测试html文件:

<!DOCTYPE html>
<html>
    <body>
        <script language="JavaScript" type="text/javascript">
            function enter() {
                this.chrono = new Date().getMilliseconds();
                alert("test");
            }
            function leave() {
                this.chrono = new Date().getMilliseconds() - this.chrono;
                var myAjax = new Ajax.Request('visitor_log/ajax_store_visit_duration.php?visit_duration=' + this.chrono.toString(),{
                        method: 'get',
                        onComplete:handlerFunction
                });
                return null;
            }
            window.onload = enter;
            window.onbeforeunload = leave;
        </script>
    </body>
</html>

PHP文件(visitor_log/ajax_store_visit_duration.PHP):

<?php
if(isset($_GET["visit_duration"]))
{
    $text = $_GET["visit_duration"];
    log($text);
}
else die("error");
function log($text)
{
    $myFile = "test.txt";
    $fh = fopen($myFile, 'wb');
    fwrite($fh, $text);
    fclose($fh);
}
?>

当我在浏览器中键入:

http://localhost/visitor_log/ajax_store_visit_duration.php?visit_duration=123

它按照我的意愿创建文本文件,但onbeforeunload事件中的AJAX调用似乎不起作用。

我的代码出了什么问题


编辑:

我创建了测试函数来查找AJAX调用的问题。

        function testajax(){
            this.chrono = new Date().getMilliseconds() - this.chrono;
           var blockingRequest = new XMLHttpRequest();
            blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + 123, false); // async = false
            blockingRequest.send();
            return null;
        }
        window.onload = testajax;
    </script>
</body>

这也不起作用。

好的,所以有目的地不使用jQuery:

这是PHP:

<?php
function loggit($text) {
    $myFile = "/tmp/test.txt";
    $fh = fopen($myFile, 'wb');
    fwrite($fh, $text);
    fclose($fh);
}
if(isset($_GET["visit_duration"])) {
    $text = $_GET["visit_duration"];
    loggit($text);
}
else die("error");
?>

这是HTML:

<!DOCTYPE html>
<html>
<body>
<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", "http://localhost/_TempFiles/temp.php?visit_duration=" + this.chrono.toString(), false); // async = false
    blockingRequest.send();
        return null;
    }
    window.onload = enter;
    window.onbeforeunload = leave;
</script>
</body>
</html>

您想要使用异步请求(请参阅发送到blockingrequest.open的false),但要注意这是一个BLOCKING请求(因此得名)。

此外,我还将php函数的名称从"log"更改为"loggit"log是php自然对数函数。。。