2012-08-04 38 views
1

我嘗試製作樣條高圖並實施How to load data from JSON to Highchart?的解決方案,這是來自Mina Gabriel的答案。代碼看起來像這樣。來自數據庫的動態樣條高圖

test.php

} 
// Set the JSON header 
header("Content-type: text/json"); 

// The x value is the current JavaScript time, which is the Unix time multiplied  by  1000. 
$x = time() * 1000; 
$y = rand(0,100) ; 



// Create a PHP array and echo it as JSON 
$ret = array($x, $y); 
echo json_encode($ret); 
?> 

而在highchart腳本:

<script> 
/** 
* Request data from the server, add it to the graph and set a timeout to request again 
*/ 
var chart; // global 
function requestData() { 
$.ajax({ 
    url: 'http://localhost:8080/test.php', 
    success: function(point) { 
     var series = chart.series[0], 
      shift = series.data.length > 20; // shift if the series is longer than 20 

     // add the point 
     chart.series[0].addPoint(point, true, shift); 

     // call it again after one second 
     setTimeout(requestData, 1000);  
    }, 
    cache: false 
    }); 
} 
$(document).ready(function() { 
    chart = new Highcharts.Chart({ 
     chart: { 
     renderTo: 'container', 
     defaultSeriesType: 'spline', 
     events: { 
      load: requestData 
     } 
    }, 
    title: { 
     text: 'Live random data' 
    }, 
    xAxis: { 
     type: 'datetime', 
     tickPixelInterval: 100, 
     maxZoom: 20 * 1000 
    }, 

    yAxis: { 
     minPadding: 0.2, 
     maxPadding: 0.2, 
     title: { 
      text: 'Value', 
      margin: 80 
     } 
    }, 
    series: [{ 
     name: 'Random data', 
     data: [] 
    }] 
    });   
}); 
    </script> 
    < /head> 
<body> 

而那些剛剛工作。但是,當我試圖改變在test.php的代碼來設置y值從數據庫這樣一個數字:

<?php 
header("Content-type: text/json"); 
$db = mysql_connect("localhost","myusername","mypassword"); 
mysql_select_db("mydatabase"); 


$day=date('Y-m-d'); //UTC standar time 

$result = mysql_query("SELECT COUNT(*) FROM table WHERE time='{$day}';"); 
$count = mysql_fetch_array($result); 

// The x value is the current JavaScript time, which is the Unix time multiplied by  1000. 
$x = time() * 1000; 
$y = $count[0]; 

// Create a PHP array and echo it as JSON 
$ret = array($x, $y); 
echo json_encode($ret); 
?> 

線圖不起作用。我檢查了SQL代碼,它的工作原理正確。我錯過了什麼?

+3

你可以請求ajax調用後返回的JSON後? – 2012-08-04 05:27:43

+1

是的,這裏需要更多信息。你可以在ajax成功回調中添加一個斷點「var series = chart.series [0]」,並分享你有的點的確切值 – 2012-08-04 05:47:35

+0

如果有任何答案有幫助,請相應地投票/標記 – 2012-08-06 21:31:05

回答

0

從給定的信息和this post,我最好的選擇是$ count [0]是一個字符串,highcharts需要它是嚴格的數字。你可以嘗試以下對我來說

$y = intval($count[0]); // OR floatval($count[0]); 
+0

是的,你是對的。 。感謝:) – user1397595 2012-08-09 15:56:42

+0

很高興。我想你現在可以標記答案 – 2012-08-09 16:40:13

+0

老實說,我不知道該怎麼做? :D怎麼樣? – user1397595 2012-08-09 16:51:03