我尝试使用Google图表绘制图表。 我的代码通过Ajax调用c#从数据库中检索数据。 dubuger不会使用c#函数,而是击中了ajax的成功函数!
Aspx:
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawchart);
function drawchart(dataValues)
{
alert("drawing function");
alert(Object.keys(dataValues).length); //alert 3
alert(Object.keys(dataValues)); // alert Message, StackTrace,ExceptionType
alert(Object.values(dataValues)); // alert Authentication failed.,,System.InvalidOperationException
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].gender, dataValues[i].cnt]);
}
new google.visualization.PieChart(document.getElementById('myChartDiv')).draw(data, { title: "Google Chart in Asp.net using jQuery" });
}
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: 'Default.aspx/getGenderCount1',
data: '{}',
success:
function (data, textStatus, xhr) {
alert(data + "\t" + textStatus);
drawchart(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
alert("Error loading data!");
}
});
})
</script>
警报看起来像这样:
[object Object] success
drawing function
3
Message,StackTrace,ExceptionType Authentication
failed.,,System.InvalidOperationException
drawing function
1
isTrusted
true
c#:
public Static List<ParticipantGender> getGenderCount1()
{
List<ParticipantGender> ListOfParticipantGender = new List<ParticipantGender>();
var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
try
{
cmd = new SqlCommand("getGenderCount", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
while (rdr.Read())
{
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
});
}
}
catch
{
}
finally
{
cmd.Dispose();
conn.Close();
}
return ListOfParticipantGender;
}
我也尝试以下操作:
公共字符串getGenderCount1()并返回结果为:var json = JsonConvert.SerializeObject(ListOfParticipantGender);返回json;
它以“无数据”绘制图表。我发现当我在c#中调试“ getGenderCount1”时,它没有调试。但是,当我将代码放入加载函数并跟踪来自数据库的数据时,它100%正确。 看来ajax不会调用c#,但是会处理ajax成功函数!!!!