我需要将一个查询从我的codeigniter传递到javascript控制台日志,以便在javascript中查看我的数据,所以我有我的模型
public function getChartData()
{
$this->db->select('Month,Completion_Percentage');
$this->db->from('monthlyreport');
$this->db->order_by('Project_No', 'asc');
$query = $this->db->get();
$result = $query->result();
$data_List = array();
foreach ($result as $row)
{
$data_List[] = $row->Month;
$data_List[] = $row->Completion_Percentage;
}
return $data_List;
}
我的控制员:
public function monthlyReport()
{
$this->load->view('monthlyReport');
}
和内部脚本:
<script type="text/javascript">
$(document).ready(function){
$.ajax({
method: 'GET',
url: '<?php echo site_url('main/chart_api')?>',
success: function (data) {
console.log(data);
},
error:function(data) {
console.log(data);
}
});
}
应该去哪里:
public function chart_api()
{
$data_List = $this->foo_pro->getChartData();
echo json_encode($data_List);
}
它显示了Uncaught SyntaxError:Unexpected token
的控制台错误答案 0 :(得分:1)
您需要在Ajax中添加dataType:“JSON”,并且
you have echo json_encode($data_List);
not return json_encode($data_List);
$.ajax({
method: 'GET',
dataType:"JSON",
url: '<?php echo site_url('main/chart_api')?>',
success: function (data) {
console.log(data);
},
error:function(data) {
console.log(data);
}
});