javascript 如何在不刷新页面的情况下连续更新 PHP 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28480728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:02:47  来源:igfitidea点击:

How can I continuously update a PHP variable without refreshing a page?

javascriptphpjqueryajax

提问by dansan

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:

我正在制作一个网站,在 Morris 图中显示来自 MySQL 数据库的数据。基本上,我有一个每分钟都会获得新测量值的数据库,我正在尝试实时显示这些更改,而无需重新加载整个页面。我已经缩短了这个问题的代码,但这里基本上是我所拥有的:

PHP code:

PHP代码:

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

And the script:

和脚本:

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

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.

然后该图形显示在一个 id 为“graph”的 div 中。所以问题是更新函数不会用新数据更新图表,因为 $data 没有得到更新。我听说我可以以某种方式创建一个 PHP 函数并使用 Ajax 连续运行它并让它更新我的 $data 变量,但我不知道如何做到这一点。

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.

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

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

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

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

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.

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

回答by sol

Edit: 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.

编辑:因为您只需要一个值,所以您的 json 将只是该值。虽然从技术上讲,这不会产生有效的 json(顶层应该有一个对象),但它与 jquery 一起工作得很好。

PHP:(data.php)

PHP:(data.php)

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

JS:

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

and that's everything to it!

这就是一切!



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.

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

You could for example use $.getJSON

例如,您可以使用 $.getJSON

Edit:The full JS would look like this:

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

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

and the response from PHP should look something like this:

PHP 的响应应该是这样的:

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

so the PHP would look like this maybe:

所以 PHP 可能看起来像这样:

[
  <?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"] . ' }';
    }
  ?>
]

回答by TRGWII

Try to put all PHP in a separate script and have it return the table in a PHP array (Use json_encode())

尝试将所有 PHP 放在一个单独的脚本中,并让它返回 PHP 数组中的表(使用 json_encode())

That way, you can use javascript to redraw the table like so:

这样,您可以使用 javascript 重新绘制表格,如下所示:

var getTableData = function(){
  $.getJSON("data.php").done(function(data){

    // code to generate html from JSON data

    $("#graph").html(tableHTML) // puts the html table into the document

    setTimeout(getTableData, 2000); // interval
  });
};
setTimeout(getTableData, 0);

I'm not sure how your data is formatted, so you'll need to create the html yourself!

我不确定您的数据是如何格式化的,因此您需要自己创建 html!

回答by zion ben yacov

You will have to use some kind of ajax call to update the value on the server. Also after updating the value you will have to save in somewhere, like in the DB or cache, because when the PHP run is over, the process dies and all the data you've created in the PHP runtime will be lost

您将不得不使用某种 ajax 调用来更新服务器上的值。同样在更新值后,您必须保存在某个地方,比如在数据库或缓存中,因为当 PHP 运行结束时,进程终止并且您在 PHP 运行时中创建的所有数据都将丢失