DataTable&HighCharts踩坑

由于要肝某个项目,为了快速开发,我又双叒叕上了JQuery的贼船,毫无意外的踩了一堆坑。现在总结一下顺便Mark。

DataTable

真的不想吐槽DataTable了,文档写的是真的烂,demo也是模模糊糊的。
百度谷歌找了一堆,跟官网API还对不上。版本兼容性也GG。

但是没办法,似乎没找到更好的。。。。

关于ajax请求后台数据

mark一下,这里等于没有用自带的ajax,而是使用了JQ的ajax外加回调函数

顺便最后一行要加一个操作行,用到了模版render

还有蛋疼的字符串拼接,要用反斜杠转义

var table;

$(document).ready(function() {
    table = $('#Table').DataTable({
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        dom: 'Bfrtip',
        buttons: [
            'excel', 'csv', 'copy', 'print'
        ],
        ajax: function(data, callback, settings) {
            $.ajax({
                type: "GET",
                url: "http://127.0.0.1:3000/alldata",
                cache: false,
                //禁用缓存
                dataType: "json",
                success: function(result) {
                    //封装返回数据
                    var returnData = {};
                    returnData.data = result; //返回的数据列表
                    //console.log(returnData);
                    //调用DataTables提供的callback方法,代表数据已封装完成并传回DataTables进行渲染
                    //此时的数据需确保正确无误,异常判断应在执行此回调前自行处理完毕
                    callback(returnData);
                }
            });
        },
        columns: [{
            data: 'source'
        }, {
            data: 'year'
        }, {
            data: 'month'
        }, {
            data: 'day'
        }, {
            data: 'category'
        }, {
            data: 'content'
        } ],
        columnDefs: [{
            targets: 6,
            render: function(data, type, row) {
                return '<div style="line-height:20px;"> <button class="btn btn-primary" data-toggle="modal" data-target="#modifyModal" id="modifiy_' + row._id + '" onclick="modifiy(\'' + row._id + '\', \'' + row.source + '\', \'' + row.year + '\', \'' + row.month + '\', \'' + row.day + '\', \'' + row.category + '\', \'' + row.content + '\');"><i class="fa fa-edit"></i>修改</button>    <button class="btn btn-danger" data-toggle="modal" data-target="#deleteModal" id="remove_' + row._id + '" onclick="remove(\'' + row._id + '\')"><i class="fa fa-pencil"></i>删除</button></div>';
            }
        }, {
            "orderable": false,
            "targets": 6
        }]
    });
});

关于ajax刷新表格

直接

table.ajax.reload();

就可以了

关于导出数据

需要加一坨js,pdf导出还乱码。。直接没用pdf了

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/buttons/1.5.2/css/buttons.dataTables.min.css" rel="stylesheet"/>

<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>

有点乱。。凑合着看吧

然后DataTable里面加上参数

dom: 'Bfrtip',
buttons: [
    'excel', 'csv', 'copy', 'print'
]

就可以了

HighCharts

讲道理,HighCharts明显比DataTable好多了,没有太多的坑。这里mark一下两个常用的图表

柱状图

var source = ['市长公开电话', '市长信箱', '网络新媒体', '区长信箱', '人民网', '文明办', '网络理政信箱督办单'];
var category = ['城市管理', '规划建设', '征地拆迁', '合同纠纷', '物业管理', '环境保护', '社会事务', '社会治安', '干部管理', '换届选举'];
var lang_setting = {
    printChart: '打印图表',
    downloadJPEG: '下载 JPEG 文件',
    downloadPDF: '下载 PDF   文件',
    downloadPNG: '下载 PNG  文件',
    downloadSVG: '下载 SVG  文件',
    downloadCSV: '下载 CSV  文件',
    downloadXLS: '下载 XLS   文件',
    viewData: '查看数据表格'
};

$("#source-chart").highcharts({
            lang: lang_setting,
            chart: {
                type: 'column',
                zoomType: 'x',
                panning: true
            },
            xAxis: {
                categories: source,
                title: {
                    text: '反映问题平台'
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: '件数 (个)'
                }
            },
            title: {
                text: '反映问题平台统计'
            },
            credits: {
                enabled: false
            },
            plotOptions: {
                column: {
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            series: [{
                name: '件数',
                data: [
                    result.filter(function (value) {return value.source == source[0]}).length,
                    result.filter(function (value) {return value.source == source[1]}).length,
                    result.filter(function (value) {return value.source == source[2]}).length,
                    result.filter(function (value) {return value.source == source[3]}).length,
                    result.filter(function (value) {return value.source == source[4]}).length,
                    result.filter(function (value) {return value.source == source[5]}).length,
                    result.filter(function (value) {return value.source == source[6]}).length,
                ]
            }]
        });

饼状图

$("#category-chart-pie").highcharts({
            lang: lang_setting,
            chart: {
            plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie'
            },
            title: {
                text: '反映问题统计饼状图'
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            credits: {
                enabled: false
            },
            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'
                        }
                    },
                    showInLegend: true
                }
            },
            series: [{
                name: '件数',
                colorByPoint: true,
                data: [{
                    name: category[0],
                    y: result.filter(function (value) {return value.category == category[0]}).length
                }, {
                    name: category[1],
                    y: result.filter(function (value) {return value.category == category[1]}).length
                }, {
                    name: category[2],
                    y: result.filter(function (value) {return value.category == category[2]}).length
                }, {
                    name: category[3],
                    y: result.filter(function (value) {return value.category == category[3]}).length
                }, {
                    name: category[4],
                    y: result.filter(function (value) {return value.category == category[4]}).length
                }, {
                    name: category[5],
                    y: result.filter(function (value) {return value.category == category[5]}).length
                }, {
                    name: category[6],
                    y: result.filter(function (value) {return value.category == category[6]}).length
                }, {
                    name: category[7],
                    y: result.filter(function (value) {return value.category == category[7]}).length
                }, {
                    name: category[8],
                    y: result.filter(function (value) {return value.category == category[8]}).length
                }, {
                    name: category[9],
                    y: result.filter(function (value) {return value.category == category[9]}).length
                }]
            }]
});

其他杂项

JSON数组过滤关键字

data.filter(function (value) {return value.key == key})

JQ获取选择的select值

$("#source-select").find("option:selected").text()

JQ ajax发送数组

似乎得stringify

$.ajax({
                type: "POST",
                url: "http://127.0.0.1:3000/new",
                dataType: "json",
                data: {
                    "data": JSON.stringify({
                        "year": selected_time[0],
                        "month": selected_time[1],
                        "day": selected_time[2],
                        "source": $("#source-select").find("option:selected").text(),
                        "category": $("#issue-select").find("option:selected").text(),
                        "subcategory": "null",
                        "title": "null",
                        "subtitle": "null",
                        "content": $("#form-content").val(),
                        "detail": $("#form-info").val() || "null",
                        "remark": $("#form-remark").val() || "null",
                        "level": 1
                    })
                },
                success: function (result) {
                    console.log(result);
                }
            });

后记

最近太忙了,昨天竟然咕掉了。。嘤嘤嘤

顺便,js牛逼!(劳资再也不想写前端了

发表评论

发表回复

*

沙发空缺中,还不快抢~