我试图从一组结果中填充一个morris.js图表。在我的控制器中,我创建了一个结果数组,并使用json_encode创建了一个json数组,下面是我使用print_r的视图中的输出:
{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2}
如何将它传递给我的morris.js图表,以使用这些数据作为标签/值对填充图表?无论我尝试什么,我要么得到一个空白图表,要么得到一个“未定义的”变量或"NaN“。这是我的控制器:
function execute_search()
{
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Get results count and pass it as json:
$data = $this->search_model->count_res('$p_results_data');
$pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0;
foreach ($data as $item) {
if ($item['result'] === 'Positive') {
$pos++;
} elseif ($item['result'] === 'Negative') {
$neg++;
} elseif ($item['result'] === 'Pending') {
$pen++;
} elseif ($item['result'] === 'Contact the Clinic') {
$cont++;
} else {
$misc++;
}
}
$res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
$data = json_encode($res);
// Use the model to retrieve results:
$this->data['results'] = $this->search_model->get_results($search_term);
$this->data['chart'] = $data;
$this->data['totals'] = $this->search_model->total_res('$total_res');
// Pass the results to the view.
$this->data['subview'] = ('user/search_results');
$this->load->view('_layout_admin', $this->data);
}
我的morris.js:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
$results
],
});
任何帮助都是非常感谢的。
发布于 2017-08-15 07:05:22
在javascript中,JSON.parse是您的朋友,假设您拥有由json_encode函数创建的JSON:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
JSON.parse( $results )
],
});
或者有可能
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( $results )
});
但我的方式
认为:
<input type="hidden" id="chartData" value='<?php echo $chart; ?>' />
在JS中(使用jQuery):
var chartData = $('#chartData').val();
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( chartData )
});
在查看了morris.js的文档之后,我发现您可以这样做:
// Looking at the docs for morris.js:
// http://jsbin.com/ukaxod/144/embed?js,output
// This is your data, but it's all in one json object
var chartData = JSON.parse( $('#chartData').val() );
// We need to break up that object into parts of the donut
var donutParts = [];
$.each( chartData, function(k,v){
donutParts.push({
label: k,
value: v
});
});
// Now create the donut
Morris.Donut({
element: 'donutEg',
data: donutParts
});
https://stackoverflow.com/questions/45692599
复制相似问题