百度echarts后台交互实例

Posted sunping177

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了百度echarts后台交互实例相关的知识,希望对你有一定的参考价值。

先看效果图,点击小图标可以切换柱状图和折线图。
选择要分析的数据01
显示为折线图
显示为柱状图
首先要做的就是下载百度echarts的包,我下载的是echarts-2.2.7,懒得找的童鞋,可以从这里下载:http://download.csdn.net/detail/sunping177/9721547
找到build下的dist文件夹,复制里面所有文件到项目中,如下图
这里写图片描述
下面我们看一下代码
先看前台页面
AnalysisSP.aspx
AjaxEcharts.js是写好的echarts于后台交互的代码

  <div style="height: 600px;" id="main"></div>
    <script src="../Content/assets/scripts/echarts/echarts.js"></script>
    <script src="../Content/assets/scripts/echarts/AjaxEcharts.js">            </script>

在这里需要说的就是需要查询的数据,在前台页面中设置隐藏域,后台对隐藏域进行赋值
例如下面代码是需要分析的条件之一,其他就不一一列举了。

                                   <span class="input-group-addon ie_widthauto">&nbsp 现居住省份&nbsp:</span>
                                <asp:DropDownList ID="ddlProviceType" runat="server" CssClass="form-control ie_widthauto">
                                    <asp:ListItem Value="-2">全部</asp:ListItem>
                                </asp:DropDownList>                              
                                <input type="hidden" id="HidddlProviceTypeV" runat="server" />                                                          

下面是AjaxEcharts.js
即echarts于后台交互的代码

$(document).ready(function () {
    var myChart;
    var eCharts;
    // 路径配置
    require.config({
        paths: {
            echarts: '../Content/assets/scripts/echarts' //echarts路径
        }
    });
    // 使用
    require(
        [
            'echarts', //echarts路径
            'echarts/chart/bar', // 使用柱状图就加载bar模块,按需加载
             'echarts/chart/line' // 使用柱状图就加载bar模块,按需加载
        ], DrawEChart//异步加载的回调函数绘制图表
        );
    //创建ECharts图表方法 
    function DrawEChart(ec) {
        eCharts = ec;
        myChart = eCharts.init(document.getElementById('main'));
        myChart.showLoading({
            text: "图表数据正在努力加载..."
        });
        //定义图表options  
        var options = {
            title: {
                text: "前台咨询登记数据分析",
                subtext: ""
            },
            tooltip: {
                trigger: "axis"
            },
            legend: {
                data: ["初始化数据"]
            },
            toolbox: {
                show: true,
                feature: {
                    mark: {
                        show: true
                    },
                    dataView: {
                        show: true,
                        readOnly: false
                    },
                    magicType: {
                        show: true,
                        type: ['line', 'bar']
                    },
                    restore: {
                        show: true
                    },
                    saveAsImage: {
                        show: true
                    }
                }
            },
            calculable: true,
            xAxis: [{
                type: 'category',
                boundaryGap: false,
                data: ['小学']
            }],
            yAxis: [{
                type: 'value',
                axisLabel: {
                    formatter: '{value}'
                },
                splitArea: {
                    show: true
                }
            }],
            grid: {
                width: '90%'
            },

            series: [{
                name: '数量',
                type: 'line',
                data: [0],//必须是Integer类型的,String计算平均值会出错  
                markPoint: {
                    data: [{
                        type: 'max',
                        name: '最大值'
                    }, {
                        type: 'min',
                        name: '最小值'
                    }]
                },
                markLine: {
                    data: [{
                        type: 'average',
                        name: '平均值'
                    }]
                }
            }]
        };
        myChart.setOption(options); //先把可选项注入myChart中  
        myChart.hideLoading();
        getChartData();//aja后台交互  
    }
    function getChartData() {
        //获得图表的options对象 
        var options = myChart.getOption();
        var hopeAnalyV = $("#hidhopeAnalyV").val();
        var hopeAnaly = $("#hidhopeAnaly").val();
        var ddlBranchV = $("#hidDDLBranchV").val();
        var ddlInfoSourceV = $("#HidddlInfoSourceV").val();
        var ddlCousultListV = $("#HidddlCousultListV").val();
        var brlCountryPartRadV = $("#HidbrlCountryPartRadV").val();

        var ddlAllRecordDepListV = $("#HidddlAllRecordDepListV").val();
        var ddlProviceTypeV = $("#HidddlProviceTypeV").val();
        var rblAllDeptRadV = $("#HidrblAllDeptRadV").val();

        var HidtxtBeginDate = $("#HidtxtBeginDate").val();
        var HidtxtEndDate = $("#HidtxtEndDate").val();

        var HidddlHopCountry = escape($("#HidddlHopCountry").val());
        var HidddlCountryGroup = escape($("#HidddlCountryGroup").val());
        var HidddlCurrentDegree = escape($("#HidddlCurrentDegree").val());
        var HidddlHopeDegree = escape($("#HidddlHopeDegree").val());
        var HidddlProvice = escape($("#HidddlProvice").val());
        //请求的参数


        if (hopeAnaly != "") {            
            //通过Ajax获取数据
            $.ajax({
                type: "post",
                async: false, //同步执行 
                url: "../Handler/EchartsData.ashx",
                data: {
                    hopeAnalyV: hopeAnalyV,
                    ddlBranchV: ddlBranchV,
                    ddlInfoSourceV: ddlInfoSourceV,
                    ddlCousultListV: ddlCousultListV,
                    brlCountryPartRadV: brlCountryPartRadV,
                    ddlAllRecordDepListV: ddlAllRecordDepListV,
                    ddlProviceTypeV: ddlProviceTypeV,
                    rblAllDeptRadV: rblAllDeptRadV,
                    HidtxtBeginDate: HidtxtBeginDate,
                    HidtxtEndDate: HidtxtEndDate,
                    HidddlHopCountry: HidddlHopCountry,

                    HidddlCountryGroup: HidddlCountryGroup,
                    HidddlCurrentDegree: HidddlCurrentDegree,
                    HidddlHopeDegree: HidddlHopeDegree,
                    HidddlProvice: HidddlProvice
                },
                dataType: "json",//返回数据形式为json 
                success: function (result) {
                    var xxlist = [];
                    var yylist = [];
                    for (var i = 0; i < result.length; i++) {
                        if (result[i].x == "") {
                            var patxx = "空";
                        } else if (result[i].x == null) {
                            var patxx = "NULL";
                        }
                        else {
                            var patxx = result[i].x;
                        }
                        var patyy = result[i].y;
                        xxlist.push(patxx);
                        yylist.push({ value: patyy, name: patxx });
                    }
                    var hpAnaly = [];
                    if (hopeAnaly != "") {
                        hpAnaly.push(hopeAnaly);
                    }
                    if (result) {
                        options.legend.data = hpAnaly;//lengend赋值数据
                        options.xAxis[0].data = xxlist;//x轴赋值数据
                        options.series[0].data = yylist;//y轴赋值数据
                        myChart.hideLoading();
                        myChart.setOption(options);
                    }
                },
                error: function (errorMsg) {
                    alert("查询数据结果为空!");
                    myChart.hideLoading();
                }
            });
        }
    }
});

echarts获取的json数据,就是从后台一般处理程序中获取的。
关键代码是
context.Response.Write(new javascriptSerializer().Serialize(list));
下面来看一般处理程序,这里传入参数很多,请自动忽略
参数中如果有传入的汉字为乱码时,可以使用标记为汉字的方法context.Server.UrlDecode()
EchartsData.ashx.cs

 public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            #region 参数
            string hopeAnalyV = context.Request["hopeAnalyV"];
            string ddlBranchV = context.Request["ddlBranchV"];
            string ddlInfoSourceV = context.Request["ddlInfoSourceV"];
            string ddlCousultListV = context.Request["ddlCousultListV"];
            string brlCountryPartRadV = context.Request["brlCountryPartRadV"];
            string ddlAllRecordDepListV = context.Request["ddlAllRecordDepListV"];
            string ddlProviceTypeV = context.Request["ddlProviceTypeV"];
            string rblAllDeptRadV = context.Request["rblAllDeptRadV"];
            string HidtxtBeginDate = context.Request["HidtxtBeginDate"];
            string HidtxtEndDate = context.Request["HidtxtEndDate"];

            //汉字
            string HidddlHopCountry = context.Server.UrlDecode(context.Request["HidddlHopCountry"]);
            string HidddlCountryGroup = context.Server.UrlDecode(context.Request["HidddlCountryGroup"]);
            string HidddlCurrentDegree = context.Server.UrlDecode(context.Request["HidddlCurrentDegree"]);
            string HidddlHopeDegree = context.Server.UrlDecode(context.Request["HidddlHopeDegree"]);
            string HidddlProvice = context.Server.UrlDecode(context.Request["HidddlProvice"]);
            #endregion
            string userid = context.Request.Cookies["userid"].Value;
            #region PowerStr
            var powerDept = DB.Context.From<Model.tblRecepPower>()
             .Select(a => a.DepartmentID)
             .Where(a => a.IsPower == 1 && a.UserID == int.Parse(userid))
             .ToList();
            string PowerStr = string.Empty;
            if (powerDept.Count > 0)
            {
                PowerStr = "and DepartmentID in (select DepartmentID from tblRecepPower  where IsPower=1 and UserID=" + userid + ")";
            }
            else
            {
                PowerStr = "";
            }

            #endregion
            #region branchid
            int userBranchid = 0;
            string userBranchName = string.Empty;
            var branchlist = DB.Context.From<Model.view_Member>()
                .Select(a => new { a.BranchID, a.BranchName })
                .Where(a => a.id == int.Parse(userid))
                .ToList();
            foreach (var item in branchlist)
            {
                userBranchid = item.BranchID;
                userBranchName = item.BranchName;
            }
            #endregion

            #region UserBranchStr
            string UserBranchStr = string.Empty;
            string ss = ddlBranchV;
            if (string.IsNullOrEmpty(ss) || ss == "-1")
            {
                UserBranchStr = "and ( BranchID in(select BranchID from tblUserBranch where Flag=1 and FuncID=2 and UserID=" + userid + ")or BranchID=0 )";
            }
            else
            {
                UserBranchStr = "and BranchID =" + ss;
            }
            #endregion
            string AnalysisTable = "view_recepinfopart";
            string strSql = string.Empty;
            if (hopeAnalyV == "HopeCountry" || hopeAnalyV == "GroupName")
            {
                AnalysisTable = "view_RecepInfoCountry";
            }

            strSql = "SELECT  count(RecepId) as y ," + hopeAnalyV + " as x";
            strSql += " from " + AnalysisTable + " where IsShow=1 " + PowerStr + UserBranchStr;
            if (HidtxtBeginDate != "" && HidtxtEndDate == "")
            {
                strSql = strSql + " and Datediff([day],RecordDate,'" + HidtxtBeginDate + "')=0 ";
            }
            else if (HidtxtBeginDate == "" && HidtxtEndDate != "")
            {
                strSql = strSql + " and  Datediff([day],RecordDate,'" + HidtxtBeginDate + "')=0 ";
            }
            else if (!string.IsNullOrEmpty(HidtxtBeginDate) && !string.IsNullOrEmpty(HidtxtEndDate))
            {
                strSql = strSql + " and RecordDate>='" + HidtxtBeginDate + " 0:00:00' and RecordDate<='" + HidtxtEndDate + " 23:59:59' ";
            }
            if (HidddlHopCountry != "全部")
            {
                strSql = strSql + " and (RecepId in(select RecepId from tblRecepHopeCountry where HopeCountry='" + HidddlHopCountry + "'))";
            }
            if (HidddlCountryGroup != "全部")
            {
                strSql = strSql + " and (RecepId in(select RecepId from view_RecepHopeCountry where GroupName='" + HidddlCountryGroup + "'))";
            }
            if (HidddlCurrentDegree != "全部")
            {
                strSql = strSql + " and CourrentDegree='" + HidddlCurrentDegree + "'";
            }
            if (HidddlHopeDegree != "全部")
            {
                strSql = strSql + " and HopeDegree='" + HidddlHopeDegree + "'";
            }
            if (brlCountryPartRadV == "1")
            {
                if (HidddlProvice != "全部")
                {
                    strSql = strSql + " and Provice='" + HidddlProvice + "'";
                }
            }
            else
            {
                if (ddlProviceTypeV != "-2")
                {
                    strSql = strSql + " and ProviceType='" + ddlProviceTypeV + "'";
                }
            }
            if (rblAllDeptRadV=="1")
            {
                if (ddlAllRecordDepListV!="-2")
                {
                      strSql = strSql + " and RecordName='" +ddlAllRecordDepListV+ "'";
                }
            }        
            if (ddlCousultListV != "-2")//咨询类型
            {
                strSql = strSql + " and ConsultType=" + ddlCousultListV + "";
            }
            if (ddlInfoSourceV != "-2")//咨询信息来源
            {
                strSql = strSql + " and (AttainInfoType=" +ddlInfoSourceV + "  or AttainInfoType=10)";
            }          
            string orderbyStr = string.Empty;
            if (hopeAnalyV== "HopeCountry")
            {
                orderbyStr = " order by HopeCountry";
            }
            else if (hopeAnalyV == "GroupName")
            {
                orderbyStr = " order by GroupName";
            }
            else if (hopeAnalyV == "BranchName")
            {
                orderbyStr = " order by BranchName";
            }
            else
            {
                orderbyStr = " order by count(RecepId) desc";
            }
            strSql += " group by " + hopeAnalyV;
            strSql += orderbyStr;

            if (hopeAnalyV == "HopeCountry" || hopeAnalyV == "GroupName")
            {
                var analyList = DB.Context.FromSql(strSql).ToList<Model.view_RecepInfoCountry>();
                var list = new List<object>();
                if (analyList.Count > 0)
                {
                    foreach (Model.view_RecepInfoCountry recpf in analyList)
                    {
                        var obj = new { x = recpf.x, y = recpf.y };
                        list.Add(obj);
                    }
                    context.Response.Write(new JavaScriptSerializer().Serialize(list));
                }
            }
            else
            {
                var analyList = DB.Context.FromSql(strSql).ToList<Model.view_Recepinfopart>();
                var list = new List<object>();
                if (analyList.Count > 0)
                {
                    foreach (Model.view_Recepinfopart recpf in analyList)
                    {
                        var obj = new { x = recpf.x, y = recpf.y };
                        list.Add(obj);
                    }
                    context.Response.Write(new JavaScriptSerializer().Serialize(list));
                }
            }



        }

==============我是结束线==================
关于echarts捣鼓了好久终于成功了,以此文勉励一下自己。也给有需要的童鞋提供方便。如有哪里不懂或我没有写清楚的地方,可以在下方留言,我看到后会第一时间回复,谢谢。

以上是关于百度echarts后台交互实例的主要内容,如果未能解决你的问题,请参考以下文章

echarts的简单应用之柱形图

百度的Echarts bar图标怎么显示百分比

小程序里echarts画的饼图在安卓手机上效果不正常?

Echarts 使用asp.net +ashx+ajax 实现 饼图柱形图后台交互

手把手教你MVC前后台数据交互Echarts写个统计图

html+js+css+接口交互+echarts实例一枚