file.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var queryObject="";
var queryObjectLen="";
$.ajax({
type : 'POST',
url : 'getdata_wordtree.jsp', //getting JSON encoded data
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length; //empdetails from getdata.jsp
},
error : function(xhr, type) {
alert('server error occoured');
}
});
google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
//two columns to show chart
data.addColumn('number', 'day'); //name of string type
data.addColumn('number', 'sales'); //empid of number type
data.addColumn('number', 'expenses'); //empid of number type
for(var i=0;i<queryObjectLen;i++)
{
//adding data from JSON retrieved
var day = queryObject.empdetails[i].day;
var sales = queryObject.empdetails[i].sales;
var expenses = queryObject.empdetails[i].expenses;
data.addRows([
[parseInt(day),parseInt(sales),parseInt(expenses)]
]);
}
var options = {
chart: {
title: 'Box Office Earnings in First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="linechart_material"></div>
</body>
</html>
我从getdata_wordtree.jsp获取JSON响应如下:{"empdetails":[{"sales":12,"day":1,"expenses":123}]}
响应很好!但图表未显示在浏览器上。我的html文件中有错误吗?我使用 Google 图表。
答案 0 :(得分:0)
有很多问题:
$.post
异步运行,您必须将工作流程更改为:
$.post
在JSAPI $.post
- 回调固定代码:
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(function(){
$.ajax({
type : 'POST',
url : 'getdata_wordtree.jsp',
dataType : 'json',
success : function(obj) {
var arr = obj.empdetails;
if(arr.length<2){
alert(arr.length +' row is not enough data, add more');
return;
}
var data = new google.visualization.DataTable(),
options = {
chart: {
title: 'Box Office Earnings in' +
'First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)'
},
width: 900,
height: 500
},
chart;
data.addColumn('number', 'day');
data.addColumn('number', 'sales');
data.addColumn('number', 'expenses');
$.each(arr,function(){
data.addRows([
[this.day,
this.sales,
this.expenses]
]);
});
chart = new google.charts
.Line(document.getElementById('linechart_material'));
chart.draw(data, options);
},
error : function(xhr, type) {
alert('server error occoured');
}
});
});
</script>
</head>
<body>
<div id="linechart_material"></div>
</body>
</html>