Django项目实战总结一----异步请求,echarts

function ajax_submit() {
    $.ajax({
        //url: "{% url 'GetIndex' %}",
        url:"/index/",
        type: "GET",
        data: {},
        success: function (arg) {
            //alert(arg.length)
            var o = $('#show_df_data')
            o.empty()
            var x = 0;
            for (var i=0; i'+x.system+' '+x.size+' '+x.used+' '+x.avail+' '+x.use+' '+x.mounted_on+'')
            }
        }
    })
}


 

先加载页面,在异步请求数据到页面;并实现实现自动和定时刷新页面

clearInterval(T1);
T1 = setInterval(function () {get_overlook_data();}, 5000);

 

class IndexView(View):
    def get(self, request):
        if not request.is_ajax():
            return render(request,'index.html',{})
        else:
            dh_infos = get_dh_infos()
            res = []
            for dh_info in dh_infos:
                res.append(json.dumps(dh_info._asdict()))
            return HttpResponse(json.dumps(res), content_type="application/json")

需要序列化数据为json格式,前台去处理json

 

2.使用echarts

1设置容器

2.使用echart function showTable(data) { var myChart = echarts.init(document.getElementById("mainAnaylsis")); var option ={xAxis:"",yAxis:"",series:[{}]} //从官网看api loadData(option);'''function {$.ajax( var result = ""; data = JSON.parse(result);//data传入option->series->data)}''' myChart.setOption(option); }

异步echart

function showTable() {
    //$('#mainAnaylsis').empty()
    var myChart = echarts.init(document.getElementById("mainAnaylsis"));
    myChart.showLoading();
    var option = {
    ]
};

    $.ajax({
        url:"zbbix_data",
        type: "GET",
        data: {},
        success: function (arg) {
            var x = 0;
            for (var i=0; i

 

 

设置可过滤的图表

 

 

    legend: {
        data:['ns值']
    },

设置图间距

    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },

 


设置其他图表格式等外部功能

 

    toolbox: {
        show : true,
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },

 

设置标签的格式和内容的展示

 

    xAxis: {
        type:'category',
        spiltLine:{
            show:true
        },
        data:[],
        axisLabel:{
            interval:3,
            rotate:40,
            formatter: function (params) {
                //console.log(params);
                //var date = Date.parse(params.toString());
                var date = new Date(params.toString().replace(/-/g,"/"));
                //console.log(date.getHours());
                return date.getHours()+':'+date.getMinutes();
            },
        },
    },

 

设置数据及加载的样式

 

    series: [
        {
            name:'ns值',
            type:'line',
            step: 'start',
            stack: '总量',
            data:[]
        },
    ]

3.使用zbbix数据库

class ZabbixDataView(View):
    def get(self, request):
        if request.is_ajax():
            infos = show_test()
            # infos = map(lambda x: x[1].strftime('%Y-%m-%d %H:%M:%S'), infos)#元组,使用map会失败
            # infos = map(lambda x:json.dumps(x), infos)
            ZB_Info = namedtuple('ZB_Info', ['itemid', 'time', 'value', 'ns']) #使用命名元组序列化数据
            res = []
            for info in infos:
                # _,t,*arg=info[1].strftime('%Y-%m-%d %H:%M:%S')
                res.append(json.dumps(ZB_Info(info[0], info[1].strftime('%Y-%m-%d %H:%M:%S'), info[2], info[3])._asdict()))//元组或者list转json
            return HttpResponse(json.dumps(res), content_type="application/json")

echart 4.1版本推荐用dataset来设置数据,

x轴为time,y轴为read和write的值的dataset格式如下

option = {
    legend: {},
    tooltip: {},
    dataset: {
        // 提供一份数据。
        source:  [
            ["time", "read", "write"], 
            ["2018-08-24 11:05:46", "39.11", "64.02"], 
            ["2018-08-24 11:05:56", "39.11", "64.02"], 
            ["2018-08-24 11:06:06", "39.11", "64.02"], 
            ["2018-08-24 11:06:16", "39.11", "64.02"], 
            ["2018-08-24 11:06:26", "39.11", "64.02"]
        ]
    },
    // 声明一个 X 轴,类目轴(category)。默认情况下,类目轴对应到 dataset 第一列。
    xAxis: {type: 'category'},
    // 声明一个 Y 轴,数值轴。
    yAxis: {},
    // 声明多个 bar 系列,默认情况下,每个系列会自动对应到 dataset 的每一列。
    series: [
        {type: 'bar'},
        {type: 'bar'}
    ]
}
tooltip的框的大小有问题,自定义大小:
tooltip:{
    trigger:'item',
    // trigger: 'none',
    // axisPointer: {
    //     type: 'cross'
    // },
    formatter:function (a) {
        return a['name']+"
"+a['value'][a['seriesIndex']+1]; }, extraCssText:'width:160px;height:40px;' },

1.tooltip的formatter,可以先console打印出a的成员函数,再调整到需要格式

2.保存上次选中的legend配置

if (io_chart.getOption().legend){
    legend_opt = io_chart.getOption().legend;//保存上次legend防止刷新掉了
}

                var legend_opt = {
                        orient: 'vertical',
                        left: 'right',
                        data: ['read', 'write', 'tps']
                };
                if (io_chart != null && io_chart != "" && io_chart != undefined) {
                    //后续加载echart时候,只用在对应位置更新局部数据
                    io_chart.setOption({
                        series: [
                        {
                            data: arg.io_info.read
                        },
                        {
                            data: arg.io_info.write
                        },

                        {
                            data: arg.io_info.tps
                        }]
                    });
                }else{
                    io_chart = echarts.init(document.getElementById("io_chart"));
                    var io_option = {
                        title: {
                            text: 'disk io'
                        },
                        legend: legend_opt,
                        tooltip: {
                            trigger: 'item',
                            // trigger: 'none',
                            // axisPointer: {
                            //     type: 'cross'
                            // },
                            formatter: function (a) {
                                return a['name'] + "
" + a['value'][a['seriesIndex'] + 1]; }, extraCssText: 'width:160px;height:40px;' }, grid: { //整体的上下左右留白 left: "3%", right: "4%", bottom: "3%", top: "15%", containLabel: true }, xAxis: { type: 'time',//只有时间格式有水平平移滚动效果,数据是放在series里面[time,value] // interval:4, splitLine:{ show:false }, axisLabel:{ //interval:0, rotate:40 } }, // 声明一个 Y 轴,数值轴。 yAxis: { scale:true, // type: 'category', splitLine:{ show:false }}, series: [ { type: 'line', name:'read',//和legend对应 animation:true, symbolSize: 2, itemStyle: { normal: {color: "#ff1c1a"} }, data: arg.io_info.read }, { type: 'line', name:'write', animation:true, symbolSize: 2, itemStyle: { normal: {color: "#2f4715"} }, data: arg.io_info.write }, { type: 'line', name:'tps', animation:true, symbolSize: 2, itemStyle: { normal: {color: "#0c06a2"} }, data: arg.io_info.tps } ] }; io_chart.setOption(io_option); }

 

你可能感兴趣的:(实验项目)