Highchars //前臺 <script> $(function () { //showChat(); initChat(); showPie(); initPie(); }) function initChat() { var xlst = []; var ylst = []; $.ajax( ...
Highchars
//前臺
<script>
$(function () {
//showChat();
initChat();
showPie();
initPie();
})
function initChat() {
var xlst = [];
var ylst = [];
$.ajax({
url: "Handler1.ashx",
data: {},
dataType: "json",
success: function (data) {
data = eval("(" + data + ")"); //序列化數據
//console.log(data);
$.each(data.Table, function (i, j) {
xlst.push(parseInt(j.day)); //push 添加數據
ylst.push(parseFloat(j.sum));
})
showChat(xlst, ylst);
//console.log(xlst);
//console.log(ylst);
}
})
}
//第一步 載入靜態樣式
function showChat(xlst, ylst) {
var chart = Highcharts.chart('container', {
chart: {
type: 'spline' //折線圖
//type: 'column' //柱狀圖
},
title: {
text: '網站每日銷售統計圖'
},
subtitle: {
text: '數據來源: 後臺統計'
},
xAxis: {
categories: xlst,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: '銷售額 (元)'
}
},
tooltip: {
// head + 每個 point + footer 拼接成完整的 table
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} ¥</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
borderWidth: 0
}
},
series: [{
name: '銷售統計',
data: ylst
}, ]
});
}
//餅狀圖
function initPie() {
var pieArr = [];
$.ajax({
url: "Handler1.ashx",
data: { op: "pie" },
dataType: "json",
success: function (data) {
data = eval("(" + data + ")"); //序列化數據
console.log(data);
$.each(data.Table, function (i,j) {//迴圈
var value = { name: j['OrdertType'], y: parseFloat(j['totalMoney']) };
pieArr.push(value);
})
//調用餅狀圖方法
showPie(pieArr);
}
})
}
//載入餅圖樣式
function showPie(pieArr) {
console.log(pieArr);
Highcharts.chart('pie', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: '所有訂單銷售占比'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: '商品類型',
colorByPoint: true,
data: pieArr
}]
});
}
</script>
//後臺
public string SqlConnectionString = ConfigurationManager.ConnectionStrings["sqlString"].ConnectionString;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
var op = context.Request.QueryString["op"];
if (op == "pie")
{
context.Response.Write(new JavaScriptSerializer().Serialize(LoadPieData()));
}
else
{
context.Response.Write(new JavaScriptSerializer().Serialize(LoadOrderData()));
}
}
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 載入曲線圖
/// </summary>
/// <returns></returns>
public string LoadOrderData()
{
string sql = @"select convert(int,DAY(CreateTime),120) as 'day',sum(OrderAmount)
as 'sum' from OrderInfo group by convert(int,DAY(CreateTime),120)
order by convert(int,DAY(CreateTime),120) asc";
DataSet ds = SqlHelper.ExecuteDataset(SqlConnectionString, CommandType.Text, sql);
//調用方法將dataset轉換為json格式的數據
var result = GetJsonByDataset(ds);
return result;
}
/// <summary>
/// 統計每個訂單類型的銷售額
/// </summary>
/// <returns></returns>
public string LoadPieData()
{
string sql = @"select SUM(OrderAmount) as totalMoney,OrdertType=Case OrdertType
when 1 then '家電'
when 2 then '生活用品'
else '其他' end
from OrderInfo group by(OrdertType)
";
DataSet ds = SqlHelper.ExecuteDataset(SqlConnectionString, CommandType.Text, sql);
//調用方法將dataset轉換為json格式的數據
var result = GetJsonByDataset(ds);
return result;
}
//StringBuilder 如果是長字元串拼接就用stringbuilder(比如sql拼接,html拼接)
//string 如果是短字元串拼接就用string
/// 把dataset數據轉換成json的格式
/// </summary>
/// <param name="ds">dataset數據集</param>
/// <returns>json格式的字元串</returns>
public static string GetJsonByDataset(DataSet ds)
{
if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
{
//如果查詢到的數據為空則返回標記ok:false
return "{\"ok\":false}";
}
StringBuilder sb = new StringBuilder();
sb.Append("{\"ok\":true,");
foreach (DataTable dt in ds.Tables)
{
sb.Append(string.Format("\"{0}\":[", dt.TableName));
foreach (DataRow dr in dt.Rows)
{
sb.Append("{");
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
sb.AppendFormat("\"{0}\":\"{1}\",", dr.Table.Columns[i].ColumnName.Replace("\"", "\\\"").Replace("\'", "\\\'"), ObjToStr(dr[i]).Replace("\"", "\\\"").Replace("\'", "\\\'")).Replace(Convert.ToString((char)13), "\\r\\n").Replace(Convert.ToString((char)10), "\\r\\n");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("},");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("],");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("}");
return sb.ToString();
}
/// <summary>
/// 將object轉換成為string
/// </summary>
/// <param name="ob">obj對象</param>
/// <returns></returns>
public static string ObjToStr(object ob)
{
if (ob == null)
{
return string.Empty;
}
else
return ob.ToString();
}