許多統計儀表盤、直播間、電商大屏需要「無刷新」實時展示在線用戶數、交易總額、匯率等動態指標。本文通過一個完整的「在線人數計數器」案例,演示如何結合 jQuery AJAX 長輪詢 與 數字滾動動畫 實現平滑的實時數據展示。
極簡 HTML,僅需一個掛載點:
<div class="count">
當前在線:<span id="number"></span>
</div>
利用 jQuery animate() 實現從當前數字平滑過渡到目標數字:
function magic_number(targetValue) {
var $num = $("#number");
// 使用虛擬屬性 count 驅動動畫
$({ count: parseInt($num.text()) || 0 }).animate({ count: targetValue }, {
duration: 500, // 動畫持續 500ms
easing: 'swing', // 緩動函數
step: function(now) { // 每幀回調
$num.text(Math.floor(now)); // 只顯示整數部分
},
complete: function() {
$num.text(targetValue); // 確保最終值精確
}
});
}
使用 $.getJSON() 發起 JSONP 請求(跨域友好),成功後觸發動畫:
function updateOnlineCount() {
$.getJSON("number.php?jsonp=?", function(data) {
// data 結構:{ "n": 123 }
if (data && typeof data.n === 'number') {
magic_number(data.n);
}
});
}
// 每 5 秒輪詢一次
setInterval(updateOnlineCount, 5000);
// 頁面載入立即執行一次
updateOnlineCount();
生產環境應查詢 Redis/Memcached/數據庫獲取真實在線數,此處用隨機數模擬:
<?php
// 設置 JSONP 回調頭
header('Content-Type: application/javascript; charset=utf-8');
// 模擬獲取在線人數(實際項目替換為真實統計邏輯)
$onlineCount = rand(0, 999);
$response = ['n' => $onlineCount];
// 輸出 JSONP 格式:callback({...})
$callback = isset($_GET['jsonp']) ? $_GET['jsonp'] : 'callback';
echo $callback . '(' . json_encode($response) . ')';
document.visibilityState)。project/
├── index.html # 包含上述 HTML + JS
└── number.php # 後端接口
通過 jQuery.animate() 虛擬屬性動畫 + JSONP 長輪詢,我們以極低成本實現了視覺友好的實時數據展示。此模式廣泛適用於「儀表盤數字跳動」、「股票價格滾動」、「投票計數器」等場景,是前端工程師必備的實用技巧。