我創建的文件api.php很好的做法,從PHP返回日期時間到JS
<?php
// Prevent caching.
header('Cache-Control: no-cache, must-revalidate');
// The JSON standard MIME header.
header('Content-type: application/json');
//mssql_select_db("**", mssql_connect(**));
$conn=mssql_connect(***);
$query = "SELECT ROUND([AirTemp_C],1) as [T]
,[DT]
FROM [ASUTP].[dbo].[Temperature_ER]
WHERE [Place] = 'ER06' AND [DT] > '26.05.2015 11:00'";
$qwr_res = mssql_query($query);
while ($row=mssql_fetch_array($qwr_res))
{
$temps[] = array (
'x' => $row['DT'],
'y' => $row['T']
);
}
echo json_encode($temps);
?>
它返回JSON像[{ 「X」: 「2015年5月26日11時02分04秒」, 「y」:26.3}]與我的測量。
我想用這個數據來繪製使用canvasjs-1.6.2的圖。這裏是我的代碼: 的window.onload =函數(){
$.getJSON("api.php",function(data1)
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Title",
fontSize: 30
},
animationEnabled: true,
zoomEnabled:true,
height: 500,
axisX:{
gridColor: "Silver",
tickColor: "silver",
labelAngle: -80,
valueFormatString: "DD.MM HH:mm"
},
toolTip:{
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend:{
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "T",
//markerType: "square",
color: "#F08080",
dataPoints: data1
}
],
legend:{
cursor:"pointer",
itemclick:function(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else{
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
});
但似乎這個圖表(或JS的話)不能使用我的日期值作爲正確的日期時間,以便圖表無法呈現。
我已經解決了這個問題,這樣的循環:
for(var i=0;i<data1.length;i++)
{
data1[i].x = new Date(data1[i].x);
}
我應該注意到我使用PHP 5.2,我不能升級。 所以我的問題是:
- 我的方式來通過api.php獲取圖表的數據是否正確?
- 有沒有辦法將正確的DateTime值從PHP傳遞給JS沒有該循環轉換?
到由於不同的瀏覽器如何解析字符串日期不同,我更喜歡通過日期爲Unix的時間戳簡單。 – Rob
你能告訴我正確的方法嗎?此外,我嚴格限制支持IE 6.0,因爲這是我們的法人規則,大多數用戶都使用IE 7/8。 – Kostya