我看到了其他帖子,但它不起作用。我对如何从 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'];
放在y :
里,$date=$row['date'];
放在x :
里,或者也许把整个桌子$table
放在var data
我是 JavaScript 的新手,所以提前感谢..!
所以在你的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
....
}
编辑/更新对于阿贾克斯...
所以对于阿贾克斯...而不是将变量分配给$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
}