jqPlot 的 JSON [英] JSON for jqPlot
问题描述
我想使用 jqPlot 使用来自服务器端的 JSON 数据,如本例中所述:http://www.jqplot.com/tests/data-renderers.php
I would like to use jqPlot usinge data from server side coming in JSON, like described in this example: http://www.jqplot.com/tests/data-renderers.php
我的代码与示例几乎相同:
My code is nearly the same like the example:
function myGraph(jsonurl) {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType:"json",
success: function(data) {
ret=data;
console.warn(data);
}
});
return ret;
};
var plot1 = $.jqplot('chartdiv', jsonurl, {
title: 'myTitle',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: { unusedOptionalUrl: jsonurl },
series: [{
label: 'myLabel',
neighborThreshold: -1
}],
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
// min:'August 1, 2010 16:00:00',
tickInterval: '2 months',
tickOptions:{formatString:'%Y-%m-%d.%H:%M:%S'}
},
yaxis: {
tickOptions:{formatString:'$%.2f'}
}
},
});
在服务器端,我使用 PHP(和 Yii).该网页返回一个数组,该数组通过使用 CJSON::encode($resultArray);
(此 Yii 函数传递给 PHP JSON 编码函数)编码为 JSON.PHP 脚本的结果如下所示:
On server side i'm using PHP (and Yii). The webpage returns an array, which is encoded to JSON by using CJSON::encode($resultArray);
(this Yii function passed trough to the PHP JSON encode function).
The Results from the PHP script lookes like that:
{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}
客户端的 Ajax 请求解决了这样的问题(来自 console.info();
的输出)
The Ajax request on client side resolved something like this (output from console.info();
)
Object { 2011-04-25 14:46:40=2, 2011-04-26 14:46:40=3, ...}
可能,jqPlot 需要以下格式:
Probably, jqPlot expect the following format:
[[["2011-04-25 14:46:40":0],["2011-04-26 14:46:40",3],["2011-04-27 14:46:40",0]]]
我总是收到 error uncaught exception: [object Object]
怎么了?有没有办法将对象转换为典型的数组形式?
All the time i get the error uncaught exception: [object Object]
What is wrong?
Is there a way to convert the object for to the typical array form?
谢谢
推荐答案
我有这样的事情.我有 2 个用于值和标签的数组.您应该从数组构造如下字符串.
I have something like this . I had 2 arrays for values,labels .You should construct string as below from arrays .
$size = count($labels);
for ($i = 0; $i < $size; $i++) {
$result = $result . "['" . $labels[$i] . "'," . $values[$i] . "]";
if($i != $size -1 ){
$result = $result . ",";
}
}
或者如果你没有 2 个数组而只有这个字符串 {"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5} 你可以用 [ , } 用 ] 和 , 用 ],[ 替换 { .一个肮脏但快速的解决方案.
OR if you dont have 2 arrays and just have this string {"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5} you can replace { with [ , } with ] and , with ],[ . A dirty but quick solution .
在上面的代码之后,你可能需要在两边附加 '[' 和 ']' 并返回值.
After above code you might need to append '[' and ']' on both sides and return value.
这篇关于jqPlot 的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!