我正在尝试从外部javascript文件调用drawChart函数。当我编译时,屏幕上显示任何内容。我无法确定问题,因为在调试过程中没有给出任何错误。
js函数中的for循环是否可以访问对象的变量。我认为错误就在那里。我发布了完整的代码以澄清。
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].name, dataValues[i].number]);
}
Default.aspx的
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("visualization", "1", { packages: ["corechart"] }); </script>
<script type="text/javascript" src="Test.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<script type="text/javascript" src="Test.js"></script>
<input type="button" onclick="drawChart('<%=getJsonObj()%>')" value="Draw Pie Chart" />
<div id="piechart" style="width: 900px; height: 500px;"></div>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string getJsonObj()
{
List<Item> data = new List<Item>();
data.Add(new Item("AAA", 10));
data.Add(new Item("BBB", 20));
data.Add(new Item("CCC", 30));
JavaScriptSerializer jss = new JavaScriptSerializer();
string json = jss.Serialize(data);
return json;
}
}
public class Item
{
public string name = "";
public int number = 0;
public Item(string iName, int iNumber)
{
name = iName;
number = iNumber;
}
}
Test.js
function drawChart(jsonObj) {
var dataValues = eval(jsonObj);
var data = new google.visualization.DataTable(dataValues);
data.addColumn('string', 'NAME');
data.addColumn('number', 'NUMBER');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].name, dataValues[i].number]);
}
var options = { 'title': 'Pie Chart Example' };
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
有人可以测试此代码并确定任何问题。感谢
答案 0 :(得分:1)
此行不正确
<input type="button" onclick="drawChart('<%=getJsonObj()%>')" value="Draw Pie Chart" />
查看渲染的源代码,您会看到JavaScriptSerializer中有一串双引号。
将其更改为:
<input type="button" onclick='drawChart( <%= getJsonObj() %> )' value="Draw Pie Chart" />
然后所有的双引号将嵌套在两个单引号
中答案 1 :(得分:0)
我认为你忘记了回调,就像这样。
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>