Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用户在网页上花费的时间_Javascript_Php_Time - Fatal编程技术网

Javascript 用户在网页上花费的时间

Javascript 用户在网页上花费的时间,javascript,php,time,Javascript,Php,Time,我如何获得花在网站上的时间,并使用ajax调用将数据保存到数据库中。我试过下面的方法,但效果不理想 <?php $ip=$_SERVER['REMOTE_ADDR']; $url=file_get_contents("http://ip-api.com/json/$ip"); //Convert the json to php associative array $data = json_decode($url, tr

我如何获得花在网站上的时间,并使用ajax调用将数据保存到数据库中。我试过下面的方法,但效果不理想

<?php

        $ip=$_SERVER['REMOTE_ADDR'];

        $url=file_get_contents("http://ip-api.com/json/$ip");

        //Convert the json to php associative array 
        $data = json_decode($url, true);


        ?>
        <html>
            <head>
                <title>My website</title>
            </head>
            <body>
                Name: <input type="text" id="name">
                <input type="submit" id="name-submit">
                <div id="name-data"></div>

                <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

            <script type="text/javascript">
                 var startTime = new Date();        
                 alert(startTime);
                 window.onbeforeunload = function(ajaxFunc) 
                 {

            var ajaxFunc = function() {
                var timeSpentMilliseconds = new Date().getTime() - startTime;
                var time = timeSpentMilliseconds / 1000 / 60;

                $.ajax({
                    type: 'GET',
                    url: 'http://example.com/get_time/index.php',
                    data: 'time=' + timeSpentMilliseconds + '&t=' + time
                });
            };

        });
            </script>
            </body>
        </html>

我的网站
姓名:
var startTime=新日期();
警报(开始时间);
window.onbeforeunload=函数(ajaxFunc)
{
var ajaxFunc=函数(){
var timespentmillizes=new Date().getTime()-startTime;
var time=TimesPent毫秒/1000/60;
$.ajax({
键入:“GET”,
网址:'http://example.com/get_time/index.php',
数据:'time='+timespentmicrosides+'&t='+time
});
};
});
快速肮脏的方法 我们将使用服务器每隔
N
秒轮询一次,手动计算用户在网站上花费的时间。为了防止累积错误,我将添加
M
(M>N)
的阈值

我所做的是设置一个数据库表,如下所示:

+--------------+------------+-------------+
| ip           | total_time | last_update |
+--------------+------------+-------------+
| 12.214.43.41 | 581        | 1456534430  |
+--------------+------------+-------------+
| 41.61.13.74  | 105        | 1456538910  |
+--------------+------------+-------------+
| 112.31.14.11 | 4105       | 1456241333  |
+--------------+------------+-------------+
然后,您就有了一个服务器端脚本,该脚本执行以下操作:

server.php

<?php
$servername = 'localhost';
$dbname     = 'cooldb';
$username   = 'dbuser';
$password   = 'changeit';
$table      = 'timers';
// Session timeout - threshold that user have left the site.
$session_timeout = 60;
$ip              = $_GET['REMOTE_ADDR'];
$now             = time();
$total_time      = 0;
$last_update     = time();
try {
    $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // Set the PDO error mode to exception
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Check if we have ip on our table
    $stmt = $db->prepare("SELECT * FROM {$table} WHERE ip=?");
    $stmt->execute([$ip]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (!empty($rows)) {
        $client      = reset($rows);
        $total_time  = $client['total_time'];
        $last_update = $client['last_update'];
        // Updating $total_time only when user is logged in and sending requests in $session_timeout timespan.
        if ($last_update + $session_timeout > $now) {
            $total_time += $now - $last_update;
        }
        $last_update = $now;
        // Client is already recorded - update the timers.
        $stmt = $db->prepare("UPDATE {$table} SET total_time=?, last_update=? WHERE ip=?");
        $stmt->execute([$ip, $total_time, $last_update]);
    } else {
        // Client have logged in first time - create a record in db.
        $stmt = $db->prepare("INSERT INTO {$table} (`ip`, `total_time`, `last_update`) VALUES ('?', '?', '?')");
        $stmt->execute([$ip, $total_time, $last_update]);
    }
} catch (PDOException $e) {
    echo $e->getMessage();
}
$db = null;
我自己还没有测试过,但我希望你能明白

// Something reasonable, below $session_timeout threshold.
var repeat = 20000;
setInterval(function(){ $.get('/server.php', function(){}); }, repeat);