如何在不刷新页面的情况下不断更新PHP变量? [英] How can I continuously update a PHP variable without refreshing a page?

查看:74
本文介绍了如何在不刷新页面的情况下不断更新PHP变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个网站,显示来自Morris图表中MySQL数据库的数据。基本上我有一个数据库,每分钟都有新的测量数据,我试图在不重新加载整个页面的情况下显示这些更改。我已经缩短了这个问题的代码,但这基本上就是我所拥有的:

I'm making a website that shows data from a MySQL database in Morris graphs. Basically I have a database that gets new measurements every minute, and I'm trying to show these changes live without having to reload the whole page. I have shortened my code for this question, but here's basically what I have:

PHP代码:

<?php
   while($measurement = mysqli_fetch_array($result)){
       $data += $measurement['data'];
   }
?>

脚本:

function data() {
        var ret = [];
        ret.push({
          y: 'Today',
          a: <?php echo $data; ?>
        });
      return ret;
    }

var graph = Morris.Bar({
        element: 'graph',
        data: data(),
        xkey: 'y',
        ykeys: ['a'],
        labels: ['random label']
    });

function update() {
      graph.setData(data());
    }

setInterval(update, 60000);

然后,图表显示在id为graph的div中。所以问题是更新功能不会使用新数据更新图表,因为$ data不会更新。我听说我可以以某种方式创建一个PHP函数并使用Ajax继续运行它并让它更新我的$ data变量,但我不知道该怎么做。

The graph is then shown in a div with the id "graph". So the problem is that the update function doesn't update the graph with new data as $data doesn't get updated. I've heard that I can somehow create a PHP function and continuously run that using Ajax and have it update my $data variable, but I have no idea how to do that.

为了更新图形,我必须重新加载整个页面,这可以使用每隔60秒刷新一次页面的元标记,但这似乎是一个糟糕的解决方案。

In order for the graph to update I have to reload the whole page, and this works fine using a meta tag that resfreshes the page every 60 seconds, but it seems like a bad solution.

我还尝试将代码放在一个单独的PHP文件中并使用以下代码运行:

I have also tried to put the code in a separate PHP file and run that using this code:

var auto_updater = setInterval(
    (function () {
        $("#graph").load("data.php");
    }), 60000);

这也可以正常工作,但问题是它会重绘整个图形并导致滚动条在我的网站上发疯。我想要的是更新Morris.Bar中的数据变量,而不是整个过程。任何帮助将不胜感激。

This also works fine, but the problem is that it redraws the whole graph and that causes the scroll bar on my site to go crazy. What I want is to update the data variable in Morris.Bar, not the whole thing. Any help would be appreciated.

推荐答案

编辑:因为你只需要一个值,你的json只会是那个值。
虽然从技术上讲,它不能生成有效的json(顶层应该有一个对象)但它可以正常使用jquery。

because you only ever need one value, your json will only be that value. Though technically that does not make for valid json (there should be an object at the top level) it works with jquery just fine.

PHP :(data.php)

PHP: (data.php)

<?php
  $data = // obtain current value of data from somewhere
  echo $data; // should be an integer
?>

JS:

$(document).ready( function () {
  var data = []; // data is empty
  var graph = Morris.Bar({
    element: 'graph',
    data: data
    labels: ['random label']
  });

  function update () {
    $.getJSON( "data.php", function (newv) {
      data.push( { x: newv, y: "Today" } ); // store new value
      graph.setData( data );                // update the graph
    });
  }

  update();
  setInterval( update, 1000 );
});

这就是它的一切!

不可能让PHP在后台运行或类似的东西,你的尝试是正确的。但是,您应该加载纯数据(例如作为JSON文档),然后通过JS将数据推送到现有数据集中,而不是加载新的HTML。
使用JS从服务器获取更新的数据是通过AJAX完成的。

It is impossible to "keep PHP running in the background" or something like that, your attempt is correct. However instead of loading new HTML you should load the pure data (for example as a JSON document) and then push that data into your existing dataset via JS. Using JS to grab updated data from the server is accomplished with AJAX.

例如,您可以使用 $。getJSON

You could for example use $.getJSON

编辑:
完整的JS看起来像这样:

The full JS would look like this:

var initial_data = <?php echo $data; ?> // or leave this out and replace with another $.getJSON for clean code!
$(document).ready( function () {
  var graph = Morris.Bar( ... );

  setInterval( function () {
    $.getJSON( "data.php", function (data) {
      graph.setData( data );
    });
  }, 1000 );
});

并且来自PHP的响应应如下所示:

and the response from PHP should look something like this:

[
  { "x": 10, "y": 20 },
  { "x": 3, "y": 12 },
  { "x": 8, "y": 19 }
]

所以PHP看起来像这样:

so the PHP would look like this maybe:

[
  <?php
    // first one seperately because it can't have a leading comma - JSON is strict
    $measurement = mysqli_fetch_array($result)
    echo '{ "x": ' . $result["data"]["x"] . ', "y": ' . $result["data"]["x"] . ' }';
    while($measurement = mysqli_fetch_array($result)) {
     // no idea what data looks like, I'm assuming it has x and y properties
     echo ', { "x": ' . $result["data"]["x"] . ', "y": ' . $result["data"]["x"] . ' }';
    }
  ?>
]

这篇关于如何在不刷新页面的情况下不断更新PHP变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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