0

我看到了其他帖子,但它不起作用。我对如何将数组从 PHP 实现到 JS 有点困惑……

在 PHP 文件(test.php)中,我有:

  $table = array();  
  while($row = mysqli_fetch_assoc($result) )  
  {

   $value=$row['value'];
   $date=$row['date'];

   $table[$value]=$date;

  }

在 JavaScript 中我有:

  <?php include 'test.php';  ?>

   ... 

  data: (function() {
  // generate an array of random data
   var data = [],
    time = (new Date()).getTime(),
    i;

   for (i = -19; i <= 0; i++) {
    data.push({
     x: time + i * 1000,
     y: Math.random()
    });
   }
   return data;

所以我要寻找的是把$value=$row['value'];andy :放在$date=$row['date'];OR 中,x : 也许把整个表$table放在var datawill 中也可以。

我是 JavaScript 新手,所以提前谢谢..!

4

1 回答 1

2

所以在你的php文件中......

在底部添加一行,将表格转换为 json 数据。并给它一个变量...

$table = array();  
 while($row = mysqli_fetch_assoc($result) )  
 {

   $value=$row['value'];
   $date=$row['date'];

   $table[$value]=$date;

 }

 $jsondata = json_encode($table);

然后在您的其他文件中......将该变量回显到您的数据对象中,在 javascript 中。记得删除整个随机数生成函数......(它只是一个例子)

将 PHP 与 javascript 相呼应绝对不是好的做法。最好对您的 php 文件进行 ajax 调用,然后像这样插入....我还将向您展示如何执行 ajax。

  <?php include 'test.php';  ?>

    ... 

   data: [<?php echo $jsondata;?>], //remove that function that was here..
   // it was just to generate random numbers for the demo
   ....
   }

编辑/更新 对于 ajax...

所以对于 ajax...而不是将变量分配给 $jsondata。像这样返回它......(在你的PHP文件中)

 return json_encode($table);

那么对于这种方式......你不include('test.php')喜欢你以前做的。相反,您只需在 $(document).ready(function(){....

$.getJSON('test.php', function(myJSON) {

 //and inside this function you put your highcharts stuff...
 //remove that function() that generates random data
 // And you will put the 'myJSON' return object inside the 'data':[] array...
 // Provided you have structured your data correctly for highcharts, it should work...
 //  If not.... it'll be a start, and you're well on your way to debugging it

}
于 2013-06-13T07:49:34.190 回答