简体   繁体   English

将php中的echo获取为javascript(单独的文件)

[英]Get echo from php into javascript (separate files)

I have been searching for hours and can't put this to work... 我一直在搜索数小时,无法使用它...

This is my first website, I have a Google gauge that need to ask a database for the value that it should put on the gauge. 这是我的第一个网站,我有一个Google仪表,该仪表需要向数据库询问应该在仪表上输入的值。 I know how to ask the database and how to update the gauge, the problem is how should I pass the echo variable from the php file to the javascript file. 我知道如何查询数据库以及如何更新量规,问题是我应该如何将echo变量从php文件传递到javascript文件。 (The php code need to be in a separate file or otherwise the google gauges won't display). (PHP代码需要在单独的文件中,否则Google仪表将不会显示)。

You can check a actual version of the website here (At the moment the gauges are static). 您可以在此处查看网站的实际版本(目前仪表是静态的)。

PHP code: PHP代码:

<?php
    $DB_NAME = 'TSB';
    $DB_HOST = 'db.tecnico.ulisboa.pt';
    $DB_USER = 'xxxxxxxxx';
    $DB_PASS = 'xxxxxxxxx';
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS);
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $mysqli->query('USE xxxxxxxxxxx;');
    $result = $mysqli->query('SELECT SOC FROM TSB ORDER By time DESC LIMIT 1;');
    $row = $result->fetch_array();
    $soc = $row['SOC'];
    echo $soc;
?>

The output of the echo is an int, or at least came as one from the database. 回声的输出是一个int,或者至少来自数据库。

What I'm trying in the javascript file: 我在javascript文件中尝试的操作:

function SOC() {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['SOC', 0]
  ]);
  var options = {
    width: 250, height: 250,
    redFrom: 0, redTo: 10,
    yellowFrom: 10, yellowTo: 25,
    minorTicks: 5,
    majorTicks: ['0','25','50','75','100']
  };
  var formatter = new google.visualization.NumberFormat({
    suffix: '%',
    fractionDigits: 0
  });
  formatter.format(data, 1);
  var chart = new google.visualization.Gauge(document.getElementById('SOC'));

  chart.draw(data, options);
  setInterval(function() {
    var socPHP;
    $.ajax({
        url: 'soc.php',
        type: 'get',
        dataType:'text',
        // I don't know how to properly put the $soc from php in a javascript variable
    });
    data.setValue(0, 1, 100); // 100 should be replaced by the value 
    //that came from the php file and the variable should be an INT
    chart.draw( data, options);
  }, 3000);
}

UPDATE After Tina Suggestion: 蒂娜建议后的更新:

<?php
  $DB_NAME = 'TSB';
    $DB_HOST = 'db.tecnico.ulisboa.pt';
    $DB_USER = 'xxxxx';
    $DB_PASS = 'xxxxx';
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS);
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $mysqli->query('USE xxxxxx;');
    $result = $mysqli->query('SELECT SOC FROM TSB ORDER By time DESC LIMIT 1;');
    $row = $result->fetch_array();
    $soc = $row['SOC'];
?>;

function SOC() {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['SOC', 0]
  ]);
  var options = {
    width: 250, height: 250,
    redFrom: 0, redTo: 10,
    yellowFrom: 10, yellowTo: 25,
    minorTicks: 5,
    majorTicks: ['0','25','50','75','100']
  };
  var formatter = new google.visualization.NumberFormat({
    suffix: '%',
    fractionDigits: 0
  });
  formatter.format(data, 1);
  var chart = new google.visualization.Gauge(document.getElementById('SOC'));

  chart.draw(data, options);
  setInterval(function() {
    data.setValue(0, 1, <?php echo $soc; ?>);
    chart.draw( data, options);
  }, 3000);
}

如果我正确理解了您的问题,请在您的javascript文件中添加所需的位置,例如,

['SOC', <?php echo $soc; ?>]

Take a look at the documentation that comes with the gauges, the data needs to be in the format: [label, value] 看一下仪表随附的文档,数据需要采用以下格式:[标签,值]

One way of achieving your goal is after you've sent your ajax request, you need to build an array in your php script and then use the json_encode function to output the data. 实现目标的一种方法是在发送ajax请求之后,需要在php脚本中构建一个数组,然后使用json_encode函数输出数据。 You'll also need to add the parameter dataType: 'JSON' to your ajax request. 您还需要将参数dataType: 'JSON'到您的Ajax请求中。

EDIT: Its frustrating reading all the comments and seeing you not get anywhere so I wrote the following which you should be able to adapt. 编辑:它令人沮丧地阅读了所有评论,看到您没有得到任何帮助,因此我写了以下您应该能够适应的书。

You need 2 files: a HTML or PHP file containing your HTML and JS, the second needs to be a PHP file containing your database query. 您需要2个文件:一个包含HTML和JS的HTML或PHP文件,第二个需要一个包含数据库查询的PHP文件。

File 1: 文件1:

<html>
  <head>
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
   <script type="text/javascript">
      google.charts.load('current', {'packages':['gauge']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['Memory', 80],
          ['CPU', 55],
          ['Network', 68]
        ]);

        var options = {
          width: 400, height: 120,
          redFrom: 90, redTo: 100,
          yellowFrom:75, yellowTo: 90,
          minorTicks: 5
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

        chart.draw(data, options);

        setInterval(function() {
            $.ajax({
                url: "g.php",
                dataType: "JSON",
                data:{},
                success: function(x){
                  data.setValue(0, 1, x["key"]);
                  chart.draw(data, options);
                }
            });
        }, 2000);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 400px; height: 120px;"></div>
  </body>
</html>

File 2, g.php (This generates a random number and outputs JSON. You can put your database query here instead of the rand() function): 文件2,g.php(这将生成一个随机数并输出JSON。您可以在此处放置数据库查询,而不是rand()函数):

<?php

    $data = array();

    $data["key"] = rand(0,100);

    print(json_encode($data));

?>

The AJAX query in the first file sends a request to file 2, g.php every 2 seconds and fetches a simple JSON object. 第一个文件中的AJAX查询每2秒向文件2(g.php)发送一个请求,并获取一个简单的JSON对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM