2017-09-18 76 views
1

時間,我從文件countrows.php此JSON輸出:谷歌圖與PHP JSON

[ 
    { 
     "time_stamp":"08:22:46 am", 
     "ph":"8", 
     "moist":"0" 
    }, 
    { 
     "time_stamp":"08:22:50 am", 
     "ph":"8", 
     "moist":"0" 
    }, 
    { 
     "time_stamp":"08:22:54 am", 
     "ph":"8", 
     "moist":"0" 
    }, 
    { 
     "time_stamp":"08:22:57 am", 
     "ph":"8", 
     "moist":"0" 
    }, 
    { 
     "time_stamp":"08:23:01 am", 
     "ph":"8", 
     "moist":"0" 
    }, 
    { 
     "time_stamp":"08:23:05 am", 
     "ph":"8", 
     "moist":"0" 
    }, 
    { 
     "time_stamp":"08:23:09 am", 
     "ph":"8", 
     "moist":"0" 
    } 
] 

這裏就是我想在我的圖表顯示的時間(從我的JSON文件來)特別是在水平方面。像下面的圖像,但黃綠線顯示從我的JSON文件的時間。

enter image description here

通過下面的方法是我的JavaScript代碼在我的谷歌的圖表,我需要什麼就用下面的代碼做幫助:

google.charts.load('current', { 
    callback: drawChart, 
    packages: ['corechart'] 
}); 

// onload callback 
function drawChart() { 
    // JSONP request 
    var jsonData = $.ajax({ 
    url: 'countrows.php', 
    dataType: 'json', 
    }).done(function (results) { 
    var data = new google.visualization.DataTable(jsonData); 

    data.addColumn('datetime', 'time_stamp'); 
    data.addColumn('number', 'ph'); 
    data.addColumn('number', 'moist'); 

    $.each(results, function (i, row) { 
     data.addRow([ 
     new Date(row.time_stamp), 
     parseFloat(row.ph), 
     parseFloat(row.moist) 
     ]); 
    }); 

    var chart = new google.visualization.AreaChart($('#chart').get(0)); 

    chart.draw(data, { 
     title: 'Soil Analysis', 
     curveType: 'function', 
     displayAnnotations: true, 
     //legend: { position: 'bottom' } 
     pointSize: 10 
     hAxis: {format: 'Y,M,d,H';} 
    }); 
    }); 
} 

drawChart(); 

setInterval(drawChart, 10000); 

回答

1

最簡單的方法是改變第一列 - >'string'

data.addColumn('string', 'time_stamp'); 

另外,由於AJAX是異步,沒必要分配給一個變量,
刪除此 - >var jsonData =

,並從參數數據表刪除構造...

var data = new google.visualization.DataTable(jsonData); // <-- remove jsonData 

試試下面的代碼片段...

google.charts.load('current', { 
    callback: drawChart, 
    packages: ['corechart'] 
}); 

// onload callback 
function drawChart() { 
    $.ajax({ 
    url: 'countrows.php', 
    dataType: 'json' 
    }).done(function (results) { 
    var data = new google.visualization.DataTable(); 
    data.addColumn('string', 'time_stamp'); 
    data.addColumn('number', 'ph'); 
    data.addColumn('number', 'moist'); 
    $.each(results, function (i, row) { 
     data.addRow([ 
     row.time_stamp, 
     parseFloat(row.ph), 
     parseFloat(row.moist) 
     ]); 
    }); 
    var chart = new google.visualization.AreaChart($('#chart').get(0)); 
    chart.draw(data, { 
     title: 'Soil Analysis', 
     curveType: 'function', 
     pointSize: 10 
    }); 
    }); 
} 
drawChart(); 
setInterval(drawChart, 10000); 
+0

太感謝你了,你從來沒有讓我失望並始終幫助我..謝謝你,謝謝你..^_^ – njhelloworld

+0

歡呼!樂意效勞... – WhiteHat