2013-07-04 49 views
0

我想用d3繪製mysql數據。我使用PHP來轉換爲JSON格式,但它不工作!出於測試目的,我按照here 所示的步驟執行,我在XAMPP上使用了simple-graph.html和我自己的php文件。json mysql數據到d3陰謀

include('connect.php'); 
$result=$con->query("SELECT date, close FROM testable");  
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC)); 

呼應JSON格式像這樣:當我提供了一個JSON文件,但不與PHP文件[{"date":"1-May-12","close":"43.32"},{"date":"30-Apr-12","close":"22.54"},{"date":"27-Apr-12","close":"21.54"},{"date":"25-Apr-12","close":"21.42"}]

圖表獲取顯示。

這工作:

d3.json("json.json", function(error, data) {   
data.forEach(function(d) {        
d.date =parseDate(d.date);       
d.close = +d.close;         
}); 

這不起作用:

d3.json("tablecreate.php", function(error, data) {  
data.forEach(function(d) {        
d.date =parseDate(d.date);       
d.close = +d.close;         
}); 

所有文件都在同一個文件夾中。

有人能指出我的錯誤嗎?

+0

當你說它不起作用時,你是什麼意思?您是否收到錯誤或不顯示您期望顯示的內容?檢查你的PHP腳本的輸出是你期望的JSON(只有JSON)。 –

+0

我收到一個空白頁。對不起,忘了那 –

+0

作爲一個測試,你可以在瀏覽器中運行你的PHP腳本,然後採取回顯結果,將它們保存在一個名爲xxx.json的文件中,然後讓頁面打開該json?只是想消除返回數據的過程正在破壞它的任何可能性。 – d3noob

回答

0

您還沒有提供完整的php源代碼,以瞭解如何將json輸出發送到您的d3腳本。一個問題是如果你沒有發送適當的內容類型頭。以下是來自d3的API參考的一些內容。

Creates a request for the JSON file at the specified url with the mime type "application/json". If a callback is specified, the request is immediately issued with the GET method, and the callback will be invoked asynchronously when the file is loaded or the request fails; the callback is invoked with two arguments: the error, if any, and the parsed JSON. The parsed JSON is undefined if an error occurs. If no callback is specified, the returned request can be issued using xhr.get or similar, and handled using xhr.on.

請確保在回顯json輸出之前發出以下語句。

header("Content-Type: application/json"); 
+1

謝謝,它沒有任何作用,它可能是一個XAMPP問題?當我使用json文件而不是本地主機時,情節顯示在瀏覽器中。 –