データベースからデータを取得するphp関数を使用して、MorrisChartのデータ引数を動的に作成しようとしています。 私のindex.phpで私は関数を呼び出し、AJAX経由でデータを読み込もうとします。私はthis answerのコードを自分のコードに実装しました。MorrisChartデータをPHP関数を介して動的に取得
<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.
?>
そして、ここでは何です。ここ
は、私は、ページのindex.php before the
`タグはの底に置く<script>
です関数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 index.php
でmorris-line-example
とdiv要素があります。私はこの設定で正常に動作するはずですが、残念ながらそれはないと思う <div id="morris-line-example" style="height: 300px"></div>
を。 AJAXリクエストに間違っていますか?
これは何も変わりません – Fabian