我想通过使用ajax,php和mysql动态构建morris.js绘图。
我一直在寻找如何实现这一目标。
我使用ajax成功获取数组数据,但现在我无法传递这些数据来构建绘图。
从PHP脚本中我得到以下json数组:
[{"concurso":"2736","R1":"7","R2":"24","R3":"27","R4":"39","R5":"45","R6":"52","R7":"12"},{"concurso":"2737","R1":"16","R2":"19","R3":"23","R4":"29","R5":"33","R6":"49","R7":"36"},{"concurso":"2738","R1":"4","R2":"6","R3":"20","R4":"21","R5":"45","R6":"55","R7":"38"},{"concurso":"2739","R1":"5","R2":"16","R3":"17","R4":"24","R5":"41","R6":"47","R7":"36"},{"concurso":"2745","R1":"1","R2":"13","R3":"19","R4":"29","R5":"41","R6":"46","R7":"50"}]
其中morris.js y 是'concurso'之后的值,而 ykeys 是 R1 之后的值, R2 < / em>, R3 ,... R7 。
到目前为止,我的jQuery看起来像这样:
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'revancha',
data: $.parseJSON(data),
xkey: 'concurso',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
我看不到情节。什么也没有。我错过了什么?
好吧,幸运的是我可以自己修理它。这是我的工作jQuery☺:$.ajax({
url: "ajax/some_handler.php",
cache: false,
type: "POST",
data: {anyVar: 'specialValue4PHPScriptAndDataBaseFilter'},
dataType: "json",
timeout:3000,
success : function (data) {
//console.log(data); alert(JSON.stringify(data));
Morris.Line({
element: 'TheElementName',
data: data,
xkey: 'someID',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
} /*References: http://stackoverflow.com/questions/22746646/ajax-i-cant-get-data-from-php-by-using-json-encode*/
});
答案 0 :(得分:1)
您可以使用Morris.Line返回对象上的setData()
函数来更新数据。以下是我所评论的莫里斯例子中的一个片段。 (https://github.com/morrisjs/morris.js/blob/master/examples/updating.html)
// build array filled with placeholder data
var nReloads = 0;
function data(offset) {
var ret = [];
for (var x = 0; x <= 360; x += 10) {
var v = (offset + x) % 360;
ret.push({
x: x,
y: Math.sin(Math.PI * v / 180).toFixed(4),
z: Math.cos(Math.PI * v / 180).toFixed(4)
});
}
return ret;
}
// create the morris chart.
var graph = Morris.Line({
element: 'graph',
data: data(0),
xkey: 'x',
ykeys: ['y', 'z'],
labels: ['sin()', 'cos()'],
parseTime: false,
ymin: -1.0,
ymax: 1.0,
hideHover: true
});
// update the chart with the new data.
function update() {
nReloads++;
// called on the returned Morris.Line object.
graph.setData(data(5 * nReloads));
$('#reloadStatus').text(nReloads + ' reloads');
}
setInterval(update, 100);