我正在尝试从一组结果填充 morris.js 图表。在我的 Controller 中,我创建了一个结果数组,并使用 json_encode 创建一个 json 数组,这是我的 View 中使用 print_r 的输出:
{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2}
如何将其传递到我的 morris.js 图表,以使用此数据作为标签/值对填充图表?我尝试的所有操作都得到一个空白图表或“未定义”变量或“NaN”。这是我的 Controller :
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
],
});
非常感谢任何帮助
最佳答案
假设你的 morris.js
是一个普通的 javascript 文件,默认情况下你不能在那里使用 php:服务器不会解析 .js
文件,因此 php 源代码代码将出现在您的 JavaScript 中。
您需要:
- 将 PHP 页面中的
morris.js
脚本内容放入 JavaScript block 中,以便解析 PHP; - 从
morris.js
脚本发出 ajax 请求,以在单独的请求中从服务器获取数据; - 设置您的服务器来解析
.js
文件,就好像它们是/包含 php 一样。
最后一个只是为了说明您需要什么,我不建议这样做。
关于javascript - 如何将 JSON 数组从 php 传递到 JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45692599/