[英]How do I put this on Real-Time? I already put (async: True) but it doesnt work
我終於使用了AJAX,但問題是,每當我在phpMyAdmin中更改一些數據時都不是實時的,我需要在網站上刷新它。
這是我的代碼: ajax.js
$(document).ready(function() {
$.ajax({
url: "http://localhost/projectZeus/private/data.php",
method: "GET",
async: true,
success: function(data) {
var energy = [];
for(var i in data) {
energy.push(data[i].energyPercent);
}
var chartdata = {
labels: ["Jan", "Feb", "Mar", "Apr", "May"],
datasets: [{
label: "Harvested",
lineTension: 0.3,
backgroundColor: "rgba(2,117,216,0.2)",
borderColor: "rgba(2,117,216,1)",
pointRadius: 6,
pointBackgroundColor: "rgba(2,117,216,1)",
pointBorderColor: "rgba(255,255,255,0.8)",
pointHoverRadius: 8,
pointHoverBackgroundColor: "rgba(2,117,216,1)",
pointHitRadius: 20,
pointBorderWidth: 2,
data: energy
}]
};
var ctx = $("#AreaChart");
var lineChart = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {
}
});
});
這是我在data.php中的代碼
<?php
require_once('initialize.php');
header('Content-Type: application/json');
global $db;
$sql = "SELECT energyPercent FROM energy";
$result = mysqli_query($db, $sql);
$data = array();
foreach($result as $row) {
$data[] = $row;
}
mysqli_free_result($result);
echo json_encode($data);
?>
如何在不刷新頁面的情況下實現它? 請幫忙,謝謝!
您可以使用服務器發送事件而不是輪詢,這不會給服務器帶來太多壓力,因為只有在發生新事件(例如新行)時才會發送數據。 有關它們的更多信息,請訪問: https : //developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
這是一個例子,因為鏈接中的那個不是那么好。
結果將類似於以下gif:
chart.html
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="chart_div"></div>
<button>Close the connection</button>
<script>
// google chart function
function chart(chart_data) {
google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Dogs');
data.addRows(chart_data);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
// stop button
var button = document.querySelector('button');
// the rest is the EventSource, simplez..
var evtSource = new EventSource('sse.php', { withCredentials: true });
evtSource.onopen = function() {
chart([])
}
evtSource.onmessage = function(e) {
chart(JSON.parse(e.data))
}
evtSource.onerror = function() {
console.log("EventSource failed.");
}
button.onclick = function() {
console.log('Connection closed');
evtSource.close();
}
/**
* or you could use addEventListener's to listen to specific events, like event: chartdata (or incase you wanted to send multiple events in the same stream)
*/
// evtSource.addEventListener("ping", function(e) {
// // do somthing with JSON.parse(e.data)
// }, false);
// evtSource.addEventListener("message", function(e) {
// // do somthing with JSON.parse(e.data)
// }, false);
</script>
</body>
</html>
然后事件循環,請注意這不是一個無限循環,也不需要維護它,一旦客戶端連接並在客戶端斷開連接后退出,它將被創建。
sse.php
<?php
// no normal requests
if ($_SERVER['HTTP_ACCEPT'] !== 'text/event-stream') {
exit();
}
// make session read-only
session_start();
session_write_close();
// disable default disconnect checks
ignore_user_abort(true);
// set headers for stream
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Access-Control-Allow-Origin: *");
// a new stream or an existing one
$lastEventId = intval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
if ($lastEventId === 0) {
// resume from a previous event
$lastEventId = intval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
}
echo ":".str_repeat(" ", 2048)."\n"; // Padding for IE
echo "retry: 2000\n";
// query initial data, or select by event id
$data = [
[0, 0],
[1, 5],
[2, 15],
[3, 45],
[4, 34],
[5, 21],
];
// mock we at event 6
$lastEventId = 6;
// start stream
while (true) {
// user disconnected, kill process
if (connection_aborted()) {
exit();
} else {
// force an update, normally you would assign ids to your events/data
$latestEventId = $lastEventId+1;
//
if ($lastEventId < $latestEventId) {
// generate some data, use array_shift() before to limit array leght whilst rolling
$data[] = [$latestEventId, rand(0, 100)];
echo "id: " . $latestEventId . "\n";
echo "event: message\n";
echo "data: ".json_encode($data)."\n\n";
$lastEventId = $latestEventId;
} else {
echo "event: ping\n";
}
}
// flush buffer
ob_flush();
flush();
// 2 second sleep
sleep(2);
}
希望它有所幫助,避免輪詢其2018年!
您可以做的是設置一個計時器,然后每n秒/分鍾執行一次ajax調用,但如果您的數據太大/太大,這是很昂貴的。 我建議使用Web套接字 ,因為這只會一次打開從服務器端到客戶端的橋接連接,然后只需要很少的資源來傳輸數據。
ref for php web socket: http : //socketo.me/
或者只是用你的javascript做計時器:
setInterval(function() {
//call your ajax function here
}, 5 * 1000) //1000 millisecond = 1 second, so multiply by 5 for 5 seconds
有兩種方法可以做到這一點(還有更多,我知道)。 首先是你創建一個不時執行這個請求的javascript函數(這將花費處理成本)。
function functionAjax () {
console.log ('Running');
}
var interval = setInterval (Ajax function, 3000);
另一個是你學習時尚的東西,RXJS,一個javascript技術,你需要一個學習的好時機。 如果它僅用於研究,我推薦FireBase(谷歌技術),它實時提供此數據庫
使用RxJS進行簡單的Ajax實現
並且總是記得在發布任何內容之前搜索,也許你找到了你正在尋找的答案,好學習=)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.