1. 程式人生 > >Django專案實戰總結一----非同步請求,echarts

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<arg.length;i++){
                x = eval("("+arg[i]+")")
                $('#show_df_data').append('<A>'+x.system+'</A> <B>'+x.size+'</B> <C>'+x.used+'</C> <D>'+x.avail+'</D> <E>'+x.use+'</E> <F>'+x.mounted_on+'</F>')
            }
        }
    })
}
<script src="../../static/js/jquery-3.3.1.js"></script>
<script language="JavaScript">
setTimeout('ajax_submit()', 10);
</script>
<script language="JavaScript"> function myrefresh(){
    ajax_submit();
    setTimeout('myrefresh()', 10000);
}
setTimeout('myrefresh()', 30000);
</script>

先載入頁面,在非同步請求資料到頁面;並實現實現自動和定時重新整理頁面

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設定容器
<p id="mainAnaylsis" style="width:750px;height:500px;"></p>

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<arg.length; i++){
                x = eval("("+arg[i]+")");
                option.series[0].data.push({name:x.time,value:[x.time,x.value]});
                option.series[1].data.push({name:x.time,value:[x.time,x.ns]});
            }
            myChart.hideLoading();
            myChart.setOption(option);//懷疑js記憶體控制原因,ajax放在另外函式裡面,setOption總是不生效
        }
    })
 }

設定可過濾的圖表

    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']+"<br/>"+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'] + "<br/>" + 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);
                }