我尝试将JSON数据插入Google电子表格。这是我的代码,
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var read=(function(){
data1={
"jobstatus": [
{
"dateAndTime": "hi",
"jobId": "TCC_tfc",
"userId": "admin",
"status": "Completed",
"jobType": "Excel Upload"
}
]
};
var jobs = data1;
var datae = new google.visualization.DataTable();
datae.addRows(["datetime",jobs.jobstatus.dateAndTime],
['jobId', jobs.jobstatus.jobId],
['userId', jobs.jobstatus.userId],
['status', jobs.jobstatus.status],
['jobType', jobs.jobstatus.jobType]
);});
</script>
执行此代码时出现错误
TypeError:google.visualization未定义
我该如何解决这个错误?我在“SO”中搜索了解决方案,他们说我要添加这一行:
google.load('visualization', '1.0', {'packages':['corechart'], 'callback': read});
通过添加它也会得到同样的错误。有人可以帮助我解决这个问题。
答案 0 :(得分:1)
这里有一些建议......
1)建议使用loader.js
与旧库jsapi
<script src="https://www.gstatic.com/charts/loader.js"></script>
2)命名callback
函数,而不是赋值给变量
google.charts.load('current', {
callback: read,
packages:['table']
});
function read(){...}
3)必须在addRows
之前添加列,有几种方法可以做到这一点,使用arrayToDataTable
很容易
var datae = google.visualization.arrayToDataTable([
['datetime', 'jobId', 'userId', 'status', 'jobType'],
]);
4)在data1
中,"jobstatus"
是一个数组,所以必须使用数组元素索引来访问值
jobs.jobstatus[0].dateAndTime // get first array element with [0]
- 或 -
如果数组中有多个jobstatus
,请使用循环将所有内容添加到addRow
jobs.jobstatus.forEach(function (job) {
datae.addRow([
job.dateAndTime,
job.jobId,
job.userId,
job.status,
job.jobType
]);
});
请参阅以下工作代码段...
google.charts.load('current', {
callback: read,
packages:['table']
});
function read(){
var data1={
"jobstatus": [{
"dateAndTime": "hi",
"jobId": "TCC_tfc",
"userId": "admin",
"status": "Completed",
"jobType": "Excel Upload"
}]
};
var jobs = data1;
var datae = google.visualization.arrayToDataTable([
['datetime', 'jobId', 'userId', 'status', 'jobType'],
]);
jobs.jobstatus.forEach(function (job) {
datae.addRow([
job.dateAndTime,
job.jobId,
job.userId,
job.status,
job.jobType
]);
});
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(datae);
}
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;