我正在尝试使用flot绘制一些从MySQL数据库提取的数据.我是登录用户的登录访问,我有一个SQL函数,它将检索给定月份每天的访问次数,即getStats($day).我已经在网上阅读了一些示例,以了解如何正确执行此操作,但是由于某些原因,当我尝试对JavaScript文件中的数组数据进行图形绘制时,它会变成空-> ‘数据:’.下面是我的代码.我正在使用CI框架,因此,如果对我的代码有任何疑问,很可能是因为这个问题.我已经对数据进行了硬编码,并且可以正常工作.在此问题上的任何帮助将不胜感激,目前关于在数据库中使用flot的内容并不多.
型号-> metrics.php
function showUsers() {
//get the number of days in the current month and the first day
$num_days = cal_days_in_month(CAL_GREGORIAN, date(m), date(Y));
$first_day = strtotime(date('Y').'-'.date('m').'-01');
//iterate through all of the days
while( $i < $num_days ) {
//get the user visits for each day of the month
$log = $this->db->getStats($first_day);
//add +1 day to the current day
$first_day += 86400;
$flot_visits[] = '['.($first_day*1000).','.$log->fields['total'].']';
$i++;
}
//format in acceptable format for flot
$content['visits'] = '['.implode(',',$flot_visits).']';
//load the view and pass the array
$this->load->vars($content);
$this->load->view('metrics/user_metrics', $content);
}
查看—> user_metrics.php
<div id ="visits_graph" style="width:600px; height:300px"></div>
Javascript —> user_metrics.js
function metrics() {
$.ajax({
type: "POST",
url: pathurl + "metrics/showUsers",
data: "",
success: function(data) {
graph_visits();
}
});
}
function graph_visits() {
$.plot($('#visits_graph'), [
{ label: 'Visits', data: <?php echo $visits ?> }
], {
xaxis: {
mode: "time",
timeformat: "%m/%d/%y"
},
lines: { show: true },
points: { show: true },
grid: { backgroundColor: #fffaff' }
});
}
解决方法:
我认为您的问题出在指标功能之内. (我也猜你在用JQuery)
目前,您的指标函数在后端请求一个页面,但不执行任何操作.
>将后端方法showUsers()更改为:
function showUsers() {
//get the number of days in the current month and the first day
$num_days = cal_days_in_month(CAL_GREGORIAN, date(m), date(Y));
$first_day = strtotime(date('Y').'-'.date('m').'-01');
//iterate through all of the days
while( $i db->getStats($first_day);
//add +1 day to the current day
$first_day += 86400;
//change this to be a nested array
$flot_visits[] = array( ($first_day*1000) , $log->fields['total'] );
$i++;
}
//output javascript array
echo json_encode( $flot_visits );
}
>将user_metrics.js更改为:
function metrics() {
$.getJSON({
pathurl + "metrics/showUsers",
function(data) {
//use the returned data
graph_visits(data);
}
});
}
function graph_visits( graphData ) {
$.plot($('#visits_graph'), [
{ label: 'Visits', data: graphData }
], {
xaxis: {
mode: "time",
timeformat: "%m/%d/%y"
},
lines: { show: true },
points: { show: true },
grid: { backgroundColor: #fffaff' }
});
}