如何将其置于实时状态?我已经把(async:True)但它不起作用 [英] How do I put this on Real-Time? I already put (async: True) but it doesnt work

查看:194
本文介绍了如何将其置于实时状态?我已经把(async:True)但它不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于使用了AJAX,但问题是,每当我在phpMyAdmin中更改一些数据时都不是实时的,我需要在网站上刷新它。



这是我的代码: ajax.js

  $(document).ready(function(){
$ .ajax({
url:http://localhost/projectZeus/private/data.php,
method: GET,
async:true,
成功:函数(数据){
var energy = [];

for(var i in data){
energy.push(data [i] .energyPercent);
}

var chartdata = {
labels:[Jan,Feb,Mar ,4月,5月,
数据集:[{
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
});
},
错误:函数(数据){

}
});
});




这是我在 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);

?>



怎么能我在不刷新页面的情况下实时获取它?请帮助,谢谢!

解决方案

您可以使用服务器发送事件而不是轮询在服务器上施加同样的压力,因为只有在发生新事件时才会发送数据(如新行)。有关它们的更多信息,请访问:



chart.html

 < HTML> 

< head>
< meta charset =UTF-8>
< title>服务器发送事件演示< / title>
< script type =text / javascriptsrc =https://www.gstatic.com/charts/loader.js>< / script>
< / head>

< body>

< div id =chart_div>< / div>

< button>关闭连接< / button>

< script>
//谷歌图表功能
功能图表(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(数据,期权);
}
}

//停止按钮
var button = document.querySelector('button');

//其余的是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();
}

/ **
*或者您可以使用addEventListener来监听特定事件,例如事件:chartdata(或者您希望在同一个流中发送多个事件)
* /
// evtSource.addEventListener(ping,function(e){
// //用JSON.parse做的事情(e.data)
// },false);

// evtSource.addEventListener(message,function(e){
// //用JSON.parse做一些事情(e.data)
//},假);
< / script>
< / body>

< / html>

那么事件循环,请注意这不是一个无限循环,你也不需要维护它,它将在客户端连接后创建,并在客户端断开连接时退出。



sse.php

 <?php 
//没有正常请求
if($ _SERVER ['HTTP_ACCEPT']!=='text / event-stream' ){
exit();
}

//使会话只读
session_start();
session_write_close();

//禁用默认断开连接检查
ignore_user_abort(true);

//为流
标头设置标头(Content-Type:text / event-stream);
header(Cache-Control:no-cache);
header(Access-Control-Allow-Origin:*);

//新流或现有流
$ lastEventId = intval(isset($ _ SERVER [HTTP_LAST_EVENT_ID])?$ _SERVER [HTTP_LAST_EVENT_ID]:0);

if($ lastEventId === 0){
//从前一个事件恢复
$ lastEventId = intval(isset($ _ GET [lastEventId])?$ _GET [lastEventId]:0);
}

echo:。str_repeat(,2048)。\ n; //填充IE
echoretry:2000 \ n;

//查询初始数据,或按事件ID选择
$ data = [
[0,0],
[1,5],
[2,15],
[3,45],
[4,34],
[5,21],
];

//模拟我们在事件6
$ lastEventId = 6;

//开始流
while(true){

//用户断开连接,kill进程
if(connection_aborted()){
exit();
} else {

//强制更新,通常你会为你的事件/数据分配id
$ latestEventId = $ lastEventId + 1;

//
if($ lastEventId< $ latestEventId){

//生成一些数据,使用array_shift()之前限制数组leght同时滚动
$ data [] = [$ latestEventId,rand(0,100)];

echoid:。 $ latestEventId。 \\\
;
echoevent:message\\\
;
echodata:。json_encode($ data)。\ n\ n;

$ lastEventId = $ latestEventId;
} else {
echoevent:ping \ n;
}
}

//刷新缓冲区
ob_flush();
flush();

// 2秒睡眠
睡眠(2);
}

希望它有所帮助,避免轮询其2018年!


I finally made it working with AJAX but the problem is, it's not real-time whenever I change some data in phpMyAdmin, I need to refresh it on the website.

Here's my code: 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) {

        }
    });
});



Here's my code in 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);

?>

How can I get it to real-time without refreshing the page? Please help, thanks!

解决方案

Instead of polling, you can use server-sent-events, which does not put as much strain on the server as data is only sent if a new event has happened (like a new row). More can be found out about them here: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

Here is an example, as the one in the link is not that good.

The result will look like the following 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>

Then the event loop, note that this is not an infinite loop nor do you need to maintain it, it will get created once a client connects and exit once the client disconnects.

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);
}

Hope it helps, avoid polling its 2018!

这篇关于如何将其置于实时状态?我已经把(async:True)但它不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆