我尝试使用从数据库获取数据的php函数动态构建MorrisChart的数据参数。 在我的index.php中,我尝试调用该函数并通过AJAX加载数据。我使用this answer中的代码将其实现为我自己的代码。
这是我放在页面底部的<script>
index.php before the
`tag:
<script type="text/javascript">
var $dataForChart1;
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
//This is where you handle what to do with the response.
//The actual data is found on this.responseText
!function($) {
"use strict";
var MorrisCharts = function() {};
//creates line chart
MorrisCharts.prototype.createLineChart = function(element, data, xkey, ykeys, labels, lineColors) {
Morris.Line({
element: element,
data: data,
xkey: xkey,
ykeys: ykeys,
labels: labels,
hideHover: 'auto',
gridLineColor: '#eef0f2',
resize: true, //defaulted to true
lineColors: lineColors
});
},
MorrisCharts.prototype.init = function() {
//create line chart
var $data = this.responseText; //<-- Here we should get the data
this.createLineChart('morris-line-example', $data, 'y', ['a', 'b'], ['Series A', 'Series B'], ['#3292e0', '#dcdcdc']);
},
//init
$.MorrisCharts = new MorrisCharts, $.MorrisCharts.Constructor = MorrisCharts;
}(window.jQuery),
//initializing
function ($) {
"use strict";
$.MorrisCharts.init();
}(window.jQuery);
};
oReq.open("get", "get-data.php", true);
// ^ Don't block the rest of the execution.
// Don't wait until the request finishes to
// continue.
oReq.send();
</script>
文件get-data.php
包含以下代码:
<?php
/* Do some operation here, like talk to the database, the file-session
* The world beyond, limbo, the city of shimmers, and Canada.
*
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX
* request. */
include("./assets/php/functions.php");
echo json_encode(getMorrisExampleData()); //In the end, you need to echo the result.
//All data should be json_encode()d.
//You can json_encode() any value in PHP, arrays, strings,
//even objects.
?>
以下是函数getMorrisExampleData()
的样子:
function getMorrisExampleData(){
$data = "[
{ y: '2009', a: 100, b: 90 },
{ y: '2010', a: 75, b: 65 },
{ y: '2011', a: 50, b: 40 },
{ y: '2012', a: 75, b: 65 },
{ y: '2013', a: 50, b: 40 },
{ y: '2014', a: 75, b: 65 },
{ y: '2015', a: 100, b: 90 }
]";
return $data;
}
当然,我的morris-line-example
中有一个ID为index.php
的div:
<div id="morris-line-example" style="height: 300px"></div>
我认为这应该可以正常使用此设置但不幸的是它没有。我是否对AJAX请求做错了什么?
答案 0 :(得分:0)
第一个问题:将getMorrisExampleData()
替换为:
function getMorrisExampleData(){
$data = array(
array("y" => 2009, "a" => 100, "b" => 90),
array("y" => 2010, "a" => 75, "b" => 65),
array("y" => 2011, "a" => 50, "b" => 40),
array("y" => 2012, "a" => 75, "b" => 65),
array("y" => 2013, "a" => 50, "b" => 40),
array("y" => 2014, "a" => 75, "b" => 65),
array("y" => 2015, "a" => 100, "b" => 90)
);
return $data;
}
为什么呢?因为在您的代码中,$data
是一个不是有效JSON的字符串。此外,当您对其进行编码时(使用json_encode
,您将其转换为不能由Morris插件使用的JSON字符串(不是具有对象的数组)。
(可能还有其他问题,请先尝试一下)