2016-08-14 110 views
1

我正在使用Google PieChart並顯示來自我的數據庫的數據。一旦用戶點擊Slice,我想讀取數據並將其傳遞給數據庫以獲取少量數據。點擊事件後,我無法從Google圖表中獲取數據。使用php和ajax在谷歌餅圖中處理事件

請在下面找到它現在使用的代碼,

var piechartdata = new google.visualization.DataTable(jsonPieChartData); 

// Instantiate and draw our pie chart, passing in some options. 
var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 


chart.draw(piechartdata, { 
    width: 700, 
    height: 200, 
    is3D: true, 
    chartArea: { left:"5%",top:"5%",width:"90%",height:"90%" } 

    var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 

    function selectHandler() { 
     var selectedItem = chart.getSelection()[0]; 
     if (selectedItem) { 
     var topping = data.getValue(selectedItem.row, 0); 
     alert('The user selected ' + topping); 
     } 
    } 

    google.visualization.events.addListener(chart, 'select', selectHandler);  
    chart.draw(data, options); 
} 

請幫助解決這個問題。

回答

0

有代碼放錯了地方,在應該是什麼options

chart.draw沒有正確關閉

和訪問數組元素

看到下面的代碼片段之前,建議您檢查的lengthchart.getSelection()
...

google.charts.load('current', { 
 
    callback: function() { 
 
    var piechartdata = google.visualization.arrayToDataTable([ 
 
     ['Task', 'Hours per Day'], 
 
     ['Work',  11], 
 
     ['Eat',  2], 
 
     ['Commute', 2], 
 
     ['Watch TV', 2], 
 
     ['Sleep', 7] 
 
    ]); 
 

 
    var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
 

 
    google.visualization.events.addListener(chart, 'select', selectHandler); 
 

 
    var options = { 
 
     width: 700, 
 
     height: 200, 
 
     is3D: true, 
 
     chartArea: { left:"5%",top:"5%",width:"90%",height:"90%" } 
 
    }; 
 

 
    chart.draw(piechartdata, options); 
 

 
    function selectHandler() { 
 
     var selectedItem = chart.getSelection(); 
 
     if (selectedItem.length > 0) { 
 
     var topping = piechartdata.getValue(selectedItem[0].row, 0); 
 
     console.log('The user selected ' + topping); 
 
     } 
 
    } 
 
    }, 
 
    packages: ['corechart'] 
 
});
<script src="https://www.gstatic.com/charts/loader.js"></script> 
 
<div id="chart_div"></div>

+0

非常感謝您的即時回覆,不幸的是,在插入給定的代碼片段後,當我點擊圖表時,它只是掛起並且沒有響應。我無法點擊任何其他切片。 – Sujith

+0

嗨whitehat在合併您建議的更改後,它給我一個錯誤無法讀取未定義的屬性getValue。 – Sujith

+0

需要在'selectHandler'中用'piechartdata'替換數據' - 上面的答案現在可以使用... – WhiteHat