我尝试使用从数据库中获取数据的php函数动态地为MorrisChart构建数据参数。 在我的index.php中,我尝试调用该函数并通过AJAX加载数据。我使用this answer的代码将其实施到我自己的代码中。通过PHP函数动态获取MorrisChart数据
这里是我放在页面底部的index.php before the
`标签<script>
:
<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;
}
当然,我有id为morris-line-example
一个div在我index.php
: <div id="morris-line-example" style="height: 300px"></div>
我认为这是应该可以正常工作与此设置只可惜事实并非如此。我的AJAX请求有问题吗?
这仍然没有改变 – Fabian