asp.net框架在后端写一个方法,通过sql语句查询数据,并将数据通过ajax接收后通过echarts输出数据的实例
时间: 2024-03-12 21:47:32 浏览: 133
好的,下面是一个简单的示例代码,基于ASP.NET框架:
后端C#代码:
using System.Data.SqlClient;
using System.Web.Script.Serialization;
public class ChartData
{
public string Name { get; set; }
public int Value { get; set; }
}
[WebMethod]
public static string GetChartData()
{
List<ChartData> chartData = new List<ChartData>();
string connectionString = "[数据库连接字符串]";
string query = "[查询语句]";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
chartData.Add(new ChartData
{
Name = reader["Name"].ToString(),
Value = Convert.ToInt32(reader["Value"])
});
}
}
}
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
return jsSerializer.Serialize(chartData);
}
前端JavaScript代码:
$.ajax({
type: "POST",
url: "PageName.aspx/GetChartData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var chartData = JSON.parse(data.d);
// 使用echarts绘制图表
// ...
},
error: function (result) {
alert("Error");
}
});
其中,[数据库连接字符串]
和[查询语句]
需要替换成实际的值,PageName.aspx
需要替换成实际的页面名称。另外,需要引入jQuery和echarts库。
相关推荐


















