我想用flot和mysql绘制图形,但是会发生异常
访问getdata.php
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
echo "[";
while($result = mysql_fetch_array($sql))
{
//print_r($result);
echo "[".$result['msgCount'].",".$result['From_user']."]"."\n";
}
echo "]";
Run Code Online (Sandbox Code Playgroud)
并为绘图
<div id="plotarea" style="width:600px;height:300px;">
<script type="text/javascript">
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
$.ajax({
url:"getData.php",
type:"post",
success:function(data)
{
alert(data);
$.plot($("#plotarea"),data,options);
//alert(data);
}
})
</script>
</div>
Run Code Online (Sandbox Code Playgroud)
这段代码有什么问题?接下来我想绘制一个轴是时间的图.
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
while($result = mysql_fetch_array($sql))
{
$user_data[] = array($result['msgCount'],$result['From_user']);
}
echo json_encode($user_data);
Run Code Online (Sandbox Code Playgroud)
以上将消除逗号分离的问题(从我所知,你从未解决过).
接下来,javascript:
<script type="text/javascript">
$(function () {
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
$.get("getData.php", function(data){
$.plot($("#plotarea"),data,options);
},
json);
});
</script>
Run Code Online (Sandbox Code Playgroud)
请注意,我更改$.ajax为$.get,因为您没有将任何数据从页面传递到脚本,所以不需要发布帖子.如果使用$.get,则假定所有设置名称.
另请注意,我将脚本从html中删除并将其放在jquery window.onload语法中:$(function () {.这将在你的HTML的头部.
据我所知,你并不真正需要ajax,因为你没有定义任何会触发$ .ajax函数的事件.当您可以将脚本放入加载页面的相同脚本时,看起来您正在使用ajax来调用脚本,例如:
<?php
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
while($result = mysql_fetch_array($sql))
{
$user_data[] = array($result['msgCount'],$result['From_user']);
}
?>
<script type="text/javascript">
$(function () {
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
var userposts = <?php echo json_encode($user_data); ?>;
$.plot($("#plotarea"),userposts,options);
</script>
<style type="text/css">
#plotarea {
width: 600px, height: 300px;
}
</style>
</head>
<body>
.....//Put whatever before the div
<div id="plotarea"></div>
.....//Finish up the page.
Run Code Online (Sandbox Code Playgroud)