dsa2c2255888 2017-01-01 19:29
浏览 40
已采纳

从php获取回声到javascript(单独的文件)

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. 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. (The php code need to be in a separate file or otherwise the google gauges won't display).

You can check a actual version of the website here (At the moment the gauges are static).

PHP code:

<?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
", 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.

What I'm trying in the javascript file:

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
", 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);
}
  • 写回答

2条回答 默认 最新

  • dtuct88226 2017-01-01 19:44
    关注

    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. You'll also need to add the parameter dataType: 'JSON' to your ajax request.

    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.

    File 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):

    <?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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog