想要从javascript文件调用php文件

时间:2019-05-14 09:58:44

标签: javascript php arrays

我有包含数组的php文件,我想从javascript文件中调用它,但我不知道方法

我尝试过这种方式,但是给了我意外的错误:

script.js文件:

  google.charts.load('current', {'packages':['corechart', 'line']});
  google.charts.setOnLoadCallback(drawLineColors);
  function drawLineColors() {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'time');
   data.addColumn('number', 'Temperature');
   data.addColumn('number', 'Humidity');

    data.addRows([  

           <?php include 'data.php' ?>

    ]);

data.php文件:

   <?php 
  $servername = "localhost";
 $database = "db";
 $username = "db";
 $password = "124";

 $connect = mysqli_connect($servername, $username, $password, $database);
 if (!$connect) {
  die("Connection failed: " . mysqli_connect_error());
  }
$query = 'SELECT * FROM climate';

$result = mysqli_query($connect, $query);


 ?>

<?php 


        if ($result->num_rows > 0) {
          while ($row = $result->fetch_assoc()) {
          echo "['".$row['time']."',".$row['temp'].",".$row['hum']."],";
           }
        }

      ?>

1 个答案:

答案 0 :(得分:1)

我假设您希望将'data.php'文件中的数组推入data.addRows

您可以使用jQuery AJAX,请找到以下代码段:

$.get('data.php',function(arr, status) {
  console.log("YOUR ARRAY HERE", arr);
})

希望有帮助!