我是一個只會用wordpress的菜鳥,
最近接到老闆指示要製作一個活動的網頁,
但不能使用wordpress,因為客戶要求。
內容會有一頁做線上直播的訊號串接跟文字對話框,
最重要的是,活動結束後需要知道使用者的基本資料、登入時間、停留的時間長度。
公司沒有專業內援可求助..
我爬了一些文 關鍵字不外乎是 php js ajax 頁面停留時間/time spent on page 等等
後來我先用了 https://www.itread01.com/p/1426659.html
這個頁面去實現,是可以計算了,
但我太菜了,技能不足,只能在顯示的時間後方多加一個提送的按鈕,
得靠使用者瀏覽完之後去觸發才能由後台紀錄。
硬著頭皮上來當伸手牌,求問有沒有更內行的方式,
可以在使用者瀏覽的同時,傳送值到後端(MYSQL)?
請小力鞭打,小的會虛心接受指教:(
以下是非常拙劣的寫法
不過至少會動
僅供參考!
api.php 裡面的 database 登入資訊要記得改!
report.sql 要匯進你的 database 裡面!
index.php
<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Welcome</title>
    </head>
    <body>
        <p>
            歡迎使用!<br />
            您已在本頁待了 <span id="text_stayTime">0</span> 秒。
        </p>
        <script>
            let clientId = -1;
            let stayTime = 0;
            let stayTimeObj = document.getElementById('text_stayTime');
            // Update stay time in html element.
            setInterval(() => {
                ++stayTime;
                stayTimeObj.innerHTML = stayTime;
            }, 1000);
            getClientId();
            // Function to get client id.
            function getClientId()
            {
                let request = new XMLHttpRequest();
                request.onreadystatechange = function() {
                    if(this.readyState == 4)
                    {
                        if(this.status == 200)
                        {
                            clientId = parseInt(request.responseText);
                            console.log('This client gets a id : ' + clientId);
                            // Execute function.
                            // Send stay time every 5 seconds.
                            setInterval(() => {
                                sendStayTime();
                            }, 5000);
                        }
                        else
                            console.log(request.responseText);
                    }
                };
                request.open('GET', 'api.php?getClientId', false);
                request.send();
            }
            // Function to send stay time to backend.
            function sendStayTime()
            {
                let request = new XMLHttpRequest();
                request.onreadystatechange = function() {
                    if(this.readyState == 4)
                    {
                        if(this.status == 200)
                        {
                            console.log('Success');
                        }
                        else
                        {
                            console.log('Failed');
                        }
                    }
                };
                request.open('GET', ('api.php?clientId=' + clientId + '&stayTime=' + stayTime), false);
                request.send();
            }
        </script>
    </body>
</html>
api.php
<?php
    ini_set('display_errors', true);
    function mysqlQuery(string $query)
    {
        $mysqlCon = mysqli_connect('hostname', 'username', 'password', 'report');
        if($mysqlCon === false)
        {
            return false;
        }
        else
        {
            $mysqlResult = mysqli_query($mysqlCon, $query) or die(mysqli_error($mysqlCon));
            mysqli_close($mysqlCon);
            return $mysqlResult;
        }
        
    }
    function mysqlQueryGetId(string $query)
    {
        $mysqlCon = mysqli_connect('hostname', 'username', 'password', 'report');
        if($mysqlCon === false)
        {
            return false;
        }
        else
        {
            mysqli_query($mysqlCon, $query) or die(mysqli_error($mysqlCon));
            $mysqlResult = mysqli_insert_id($mysqlCon);
            mysqli_close($mysqlCon);
            return $mysqlResult;
        }
        
    }
    if(isset($_GET['getClientId']))
    {
        $clientId = mysqlQueryGetId('INSERT INTO record (stayTime) VALUES (0);');
        if($clientId !== false)
        {
            http_response_code(200);
            echo $clientId;
        }
        else
        {
            http_response_code(500);
        }
    }
    else if(isset($_GET['clientId']) && isset($_GET['stayTime']))
    {
        $clientId = (int)$_GET['clientId'];
        $stayTime = (int)$_GET['stayTime'];
        $mysqlResult = mysqlQuery("UPDATE record SET stayTime = $stayTime WHERE id = $clientId;");
        if($mysqlResult !== false)
        {
            http_response_code(200);
        }
        else
        {
            http_response_code(500);
        }
    }
    else
        header('Location: index.php');
report.sql
-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jul 11, 2021 at 09:10 PM
-- Server version: 8.0.25-0ubuntu0.20.04.1
-- PHP Version: 7.4.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+08:00";
--
-- Database: `report`
--
CREATE DATABASE IF NOT EXISTS `report` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `report`;
-- --------------------------------------------------------
--
-- Table structure for table `record`
--
CREATE TABLE `record` (
  `id` int NOT NULL,
  `stayTime` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `record`
--
ALTER TABLE `record`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `record`
--
ALTER TABLE `record`
  MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;
                這老闆也太折騰員工了。
這個需要會寫後端程式+前端程式,都不是短時間可以學會的。
你要找會寫程式的好朋友幫你,或是請老闆找外包。