这是我今天正在努力解决的问题:
我正在尝试使用 jqPlot 库绘制图形。
sql 查询输出数据,在 php 中使用 json_encode
转换为 json并保存在隐藏的表单字段中。这工作正常,实际字段包含:
[["2011-12-10 12:01:00",271],["2011-12-10 12:13:05",132],["2011-12-11 12:17:55",388],["2011-12-10 22:03:40",5],["2011-12-11 12:10:54",830]]
然后使用 javascript 从表单中检索数据:
var data = document.getElementById("dataarray").value;
以便稍后将其用作 jqPlot 的数据。
data
变量格式正确并使用 document.write(data);
检查时,以 json 格式输出正确的数据,但每当我将它放在 plot1
中时变量为图形使用数据会引发错误 [object Object]
在 Safari 和 Uncaught #<Object>
在 Firefox 中。
整个javascript代码如下:
$(document).ready(function(){
var data = document.getElementById("dataarray").value;
var test = [["2011-12-10 12:01:00",271],["2011-12-10 12:13:05",132],["2011-12-11 12:17:55",388],["2011-12-10 22:03:40",5],["2011-12-11 12:10:54",830]];
var plot1 = $.jqplot("chart_personal_2", [data], {
title:"Data Point Highlighting",
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer,
numberTicks: 3,
tickOptions:{
formatString:"%d/%m/%Y %H:%M:%S"
}
},
yaxis:{
label: "Elevation(m)",
tickOptions:{
showMark: true
}
}
},
highlighter: {
show: true,
sizeAdjust: 7.5
},
cursor: {
show: false
}
});
});
我什至试过output = String(data);
但它也没有用。
我假设我的 data
变量是一个对象,不能用作jqPlot图的源数据,使用前需要转换成字符串吗?如果我错了,请纠正我。
希望有人知道如何解决这个问题,在此先感谢!
最佳答案
你正在检索它作为 String
,但是 jqPlot
需要 Array
,所以你必须运行 eval
它:
var data = document.getElementById("dataarray").value;
eval('data = '+data+';');
或更好的解决方案:不要将其保存到隐藏输入,而是从 php 中创建 JS 变量:
echo "<script type='text/javascript'> var data = ".json_encode($data).";</script>";
关于php - 如何将 json 从 php 传递到 jqPlot 的 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8494014/