我创建了一个到我的数据库的 PHP 连接并进行了以下查询:
$taxRates = array();
while($row = mysql_fetch_assoc($result)) {
$taxRates[] = $row['mar_tax_rate'];
}
然后我将结果编码如下:
$jsonobj = json_encode($taxRates, JSON_NUMERIC_CHECK);
echo "This is jsonobj:<br>" . $jsonobj . "<br>";
返回:
This is jsonobj:
[0,0.35,0.35,0.35,0.35,0.35,0.35,0.35,0.35]
我遇到的问题是这个。当我尝试将这些结果回显到 JS 中时,我的结果是空的(据我所见)——不是空数组,什么都没有。这就是我试图将结果输入 JS 的方式:
data:[<?php echo $jsonobj; ?>]
返回:
data:
我试图使用警告 PHP 变量
alert("<?php echo $jsonobj; ?>");
这会产生警报,但也是空的。
有什么想法吗?
这是完整的代码:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script type="text/javascript" src="includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="includes/js/highcharts.2.3.2.js"></script>
<script type="text/javascript" src="includes/js/highstock.src.js"></script>
<script type="text/javascript">
$(document).ready(function() {
drawChart();
});
function drawChart() {
alert("<?php echo join($jsonobj); ?>");
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
type: 'column',
},
credits: {
enabled: false
},
series: [{
data:[<?php echo $jsonobj; ?>]
}]
});
};
</script>
</head>
<body>
<button style="height:100px; width:300px;" onclick="drawChart();">Redraw the Chart</button><br />
<div id="chart"></div>
<?php
$link = mysql_connect('url', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//mysql_close($link);
$db_selected = mysql_select_db('bloch',$link);
if (!$db_selected) {
die ('Can\'t use Bloch Database : ' . mysql_error());
}
$result = mysql_query('SELECT mar_tax_rate from bloch.bloch_deficit');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$taxRates = array();
while($row = mysql_fetch_assoc($result)) {
$taxRates[] = $row['mar_tax_rate'];
}
$jsonobj = json_encode($taxRates, JSON_NUMERIC_CHECK);
echo "This is jsonobj:<br>" . $jsonobj . "<br>";
?>
</body>
</html>