[英]Pass a array from one function to another
我有这段代码可以从xml文件中获取数据。 我需要将这些数据提供给当前位于数组中的Google图表。 我需要将xml值传递到Google图表。 谁能帮我解决这个问题。 下面是我的代码。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var values = [];
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
values.push([sTitle, sValue]);
});
drawChart(values);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
function drawChart(val) {
alert(val);
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<title>My Read</title>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Xml文件
<?xml version="1.0" encoding="utf-8" ?>
<Chart>
<Pie>
<Title>Task</Title>
<Value>Hours per Day</Value>
</Pie>
<Pie>
<Title>Work</Title>
<Value>11</Value>
</Pie>
<Pie>
<Title>Eat</Title>
<Value>2</Value>
</Pie>
<Pie>
<Title>Commute</Title>
<Value>2</Value>
</Pie>
<Pie>
<Title>Watch TV</Title>
<Value>2</Value>
</Pie>
<Pie>
<Title>Sleep</Title>
<Value>7</Value>
</Pie>
</Chart>
改变这个
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
至
var data = google.visualization.arrayToDataTable((Array.isArray(val) && val.length) ? val : [
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
如果value数组且不为空-将val
传递给函数,否则传递默认选项。
您还需要将sValue
从字符串转换为数字,像这样
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
if (!isNaN(+sValue)) {
sValue = +sValue;
}
values.push([sTitle, sValue]);
});
您已经将该数组传递给drawChart()
函数,
drawChart(values);
希望它能正常工作。
也许您只是通过两次调用drawChart
混淆自己:一次在google.setOnLoadCallback(drawChart)
,一次在成功函数中。 删除setOnLoadCallback
的一个(或创建一个关注两者的加载状态并在加载两者时调用drawChart
)。 并实施亚历山大的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.