iT邦幫忙

0

網頁停留時間獲取後,如何自動提送至後端接收?

  • 分享至 

  • xImage

我是一個只會用wordpress的菜鳥,
最近接到老闆指示要製作一個活動的網頁,
但不能使用wordpress,因為客戶要求。

內容會有一頁做線上直播的訊號串接跟文字對話框,
最重要的是,活動結束後需要知道使用者的基本資料、登入時間、停留的時間長度。

公司沒有專業內援可求助..

我爬了一些文 關鍵字不外乎是 php js ajax 頁面停留時間/time spent on page 等等
後來我先用了 https://www.itread01.com/p/1426659.html
這個頁面去實現,是可以計算了,
但我太菜了,技能不足,只能在顯示的時間後方多加一個提送的按鈕,
得靠使用者瀏覽完之後去觸發才能由後台紀錄。

硬著頭皮上來當伸手牌,求問有沒有更內行的方式,
可以在使用者瀏覽的同時,傳送值到後端(MYSQL)?

請小力鞭打,小的會虛心接受指教:(

看更多先前的討論...收起先前的討論...
haward79 iT邦研究生 2 級 ‧ 2021-07-11 06:04:19 檢舉
前端可以用 js 的 setTimeout 定時送前端停留的時間到後端
再由後端的 api 接收,然後儲存到 MySQL
94ariel iT邦新手 5 級 ‧ 2021-07-11 06:08:17 檢舉
太感動了,一大早的居然有人回覆QQ<
但我...到aqi那行就斷軌了.... 請問我可以再向你請教更多嗎
Todd iT邦新手 1 級 ‧ 2021-07-11 20:00:19 檢舉
用 setInterval
看你的原文目前可以按鈕call api到後台了
那其實只要把那個function 放到 setInterval 裡應該就可以了
froce iT邦大師 1 級 ‧ 2021-07-12 10:12:04 檢舉
這不是只會wp的人可以處理的,建議外包。

然後這用websocket應該會比用setInterval好。
Todd iT邦新手 1 級 ‧ 2021-07-12 10:18:15 檢舉
我是覺得如果只是「單純記錄時間」並打API到後台紀錄
後端沒有要根據目前紀錄時間有什麼動作的話
感覺是不需要用到websocket
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
haward79
iT邦研究生 2 級 ‧ 2021-07-11 21:15:57
最佳解答

以下是非常拙劣的寫法
不過至少會動
僅供參考!

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;
1
sx0800
iT邦新手 1 級 ‧ 2021-07-11 08:54:09

這老闆也太折騰員工了。
這個需要會寫後端程式+前端程式,都不是短時間可以學會的。
你要找會寫程式的好朋友幫你,或是請老闆找外包。

我要發表回答

立即登入回答