• Django前端页面利用ajax动态显示数据


    以下代码是某个项目中的一部分,无法直接使用。

    1、需要有一个试图返回数据据(数据API)

    def dataYear(request):
        """
           统计所有数据的界面, 生成年份标签
        """
        year = request.GET['year']
        table_type = request.GET['table']
        cursor = connections['stats'].cursor()
    
        provinceSql = "SELECT DISTINCT province FROM YEAR_DATA_QUALITY_VIEW WHERE table_type='crawlerapp_results_history'"
        cursor.execute(provinceSql)
        company_year_records = cursor.fetchall()
        provinces_list = []
        for company_year_record in company_year_records:
            provinces_list.append(company_year_record[0])
    
        detail_info = {}
    
        # 创建月份的统计数据视图
        for province in provinces_list:
            detail_info[province] = {}
            yearSql = "SELECT syear, province, records_count FROM YEAR_DATA_QUALITY_VIEW WHERE table_type='%s' AND province='%s' AND syear='%s' ORDER BY syear" % (
                table_type, province, year)
            cursor.execute(yearSql)
            company_year_records = cursor.fetchall()
            if len(company_year_records) > 0:
                detail_info[province]['year'] = company_year_records[0][0]
                detail_info[province]['province'] = company_year_records[0][1]
                detail_info[province]['year_total'] = company_year_records[0][2]
            else:
                context = {'detail_info': {}}
                return HttpResponse(json.dumps(context))
    
            monthSql = "SELECT syear, province, month, records_count FROM month_results_view WHERE table_type='%s' AND province='%s' AND syear='%s' ORDER BY month" % (
                table_type, province, year)
            cursor.execute(monthSql)
            company_month_records = cursor.fetchall()
            # detail_info[province][''] = company_month_records[0][0] #年份
            # detail_info[province][''] = company_month_records[0][1] #省份
            # detail_info[province]['month_data'] ={}
            for init_month in range(1, 13):
                detail_info[province]['month' + str(init_month)] = '暂无数据'
            for month_data in company_month_records:
                # detail_info[province][month_data[2]] = month_data[2] #月份
                detail_info[province]['month' + str(month_data[2])] = month_data[3]  # 数据量
    
            baseInfoSql = "SELECT syear, company_count, monitor_count, monitor_info_count FROM COMPANY_BASE_INFO_VIEW WHERE province='%s' AND syear='%s' ORDER BY syear" % (
                province,year)
            cursor.execute(baseInfoSql)
            company_base_infos = cursor.fetchall()
            # detail_info[province]['base_info'] ={}
            detail_info[province]['base_year'] = company_base_infos[0][0]
            detail_info[province]['base_company_count'] = company_base_infos[0][1]
            detail_info[province]['base_monitor_count'] = company_base_infos[0][2]
            detail_info[province]['base_monitor_info_count'] = company_base_infos[0][3]
    
        context = {'detail_info': detail_info}
        # return render(request, 'test.html', context)
        print 'data year', '-'*50
        return HttpResponse(json.dumps(context))
    View Code

    2、需要一个视图对数据进行渲染

    def dataOverview(request):
        """
        统计所有数据的界面, 生成年份标签
        """
        cursor = connections['stats'].cursor()
        # 获取视图中的年份
        yearSql = "SELECT DISTINCT syear FROM YEAR_DATA_QUALITY_VIEW WHERE table_type='crawlerapp_results_history'"
        cursor.execute(yearSql)
        company_year_records = cursor.fetchall()
        year_list = []
        for company_year_record in company_year_records:
            year_list.append(company_year_record[0])
    
        context = {'year_list': year_list}
        return render(request, 'overview.html', context)
    View Code

    3、使用ajax

    {% extends 'new_base.html' %}
    
    {% block grid %}
    <div class="ui equal width grid" style="margin:5px 0 5px 0;70%">
    
    {#  ------------------------------------------------ CHART BLOCK ---------------------------------------------------  #}
        <div class="row">
          <div class="column">
            <div class="ui container segment">
                <div class="ui compact menu">
    
                    <select name="year" class="ui dropdown" id="year">
                        <option value="">年份</option>
                        {% for year in year_list %}
                            <option class="item py_item" value={{year}}>{{year}}</option>
                        {% endfor %}
                    </select>
    
                    <select name="table_type" class="ui dropdown" id="table">
                        <!--<option value="">Gender</option>-->
                        <option value="crawlerapp_results_history">历史监测数据</option>
                        <option value="crawlerapp_results">实时监测数据</option>
                    </select>
                </div>
                {#                表格1#}
                <div class="table-container">
                    <table class="ui nine column table celled table-result" id="table-result">
                        <thead>
                            <tr>
                                <th>省份</th>
                                <th>监测数据总数</th>
                                <th>1月</th>
                                <th>2月</th>
                                <th>3月</th>
                                <th>4月</th>
                                <th>5月</th>
                                <th>6月</th>
                                <th>7月</th>
                                <th>8月</th>
                                <th>9月</th>
                                <th>10月</th>
                                <th>11月</th>
                                <th>12月</th>
                            </tr>
                        </thead>
                        <tbody id="tbody-result">
                        </tbody>
                    </table>
                </div>
                 {#                表格1#}
                <div class="table-container">
                    <table class="ui nine column table celled table-result" id="table-result2">
                        <thead>
                            <tr>
                                <th>省份</th>
                                <th>公司数量</th>
                                <th>监测点数量</th>
                                <th>监测因在数量</th>
                            </tr>
                        </thead>
                        <tbody id="tbody-result2">
                        </tbody>
                    </table>
                </div>
    
    
    
            </div>
          </div>
        </div>
    {#  ------------------------------------------------ CHART BLOCK ---------------------------------------------------  #}
    </div>
    {% endblock %}
    
    
    
    {% block table %}
         <script>
    //        年份下拉框的改变事件
            $('#year')
              .dropdown({
    //            action: 'hide',
                  onChange: function (value, text, $selectedItem) {
    //              获取表类型参数
                      var tableType = $('#table').dropdown('get value')[0];
                      var tableTypeText = $('#table').dropdown('get text')[0];
                      console.log((tableType));
    //            获取选中年份的字段
                      var year = value;
                      console.log((year))
                      var tbody=window.document.getElementById("tbody-result");
                      var tbody2=window.document.getElementById("tbody-result2");
                      $.ajax({
                          url:"year/?year="+year+"&table=" + tableType,
                          type:'GET',
                          success:function (msg) {
    {#                          反序列化#}
                              var data = eval('(' + msg + ')');
                              console.log(typeof(msg));
                              var table_data = data['detail_info'];
                              console.log(table_data)
                              var str1 = '';
                              var str2 = '';
                              if (!table_data){
                                  tbody.innerHTML='';
                                  tbody2.innerHTML='';
                                  return
                              }
                              for ( k in table_data){
                                  console.log(k)
                                  str1 += "<tr>" +
                                      "<td>"+ table_data[k]['province'] +"</td>" +
                                      "<td>"+ table_data[k]['year_total'] +"</td>" +
                                      "<td>"+ table_data[k]['month1'] +"</td>" +
                                      "<td>"+ table_data[k]['month2'] +"</td>" +
                                      "<td>"+ table_data[k]['month3'] +"</td>" +
                                      "<td>"+ table_data[k]['month4'] +"</td>" +
                                      "<td>"+ table_data[k]['month5'] +"</td>" +
                                      "<td>"+ table_data[k]['month6'] +"</td>" +
                                      "<td>"+ table_data[k]['month7'] +"</td>" +
                                      "<td>"+ table_data[k]['month8'] +"</td>" +
                                      "<td>"+ table_data[k]['month9'] +"</td>" +
                                      "<td>"+ table_data[k]['month10'] +"</td>" +
                                      "<td>"+ table_data[k]['month11'] +"</td>" +
                                      "<td>"+ table_data[k]['month12'] +"</td>" +
                                  "</tr>"
                                  str2 += "<tr>"+
                                            "<td>"+ table_data[k]['province'] +"</td>" +
                                            "<td>"+ table_data[k]['base_company_count'] +"</td>" +
                                            "<td>"+ table_data[k]['base_monitor_count'] +"</td>" +
                                            "<td>"+ table_data[k]['base_monitor_info_count'] +"</td>" +
                                          "</tr>"
                              }
                              tbody.innerHTML = str1;
                              tbody2.innerHTML = str2;
    
                          }
                      })
    
                  }
              });
            //        实时表或是历史表的改变类型触发
            $('#table')
              .dropdown({
    //            action: 'hide',
                  onChange: function (value, text, $selectedItem) {
    //                console.log(value, text);
    //                  获取表类型参数
                      var year = $('#year').dropdown('get value')[0];
    //                如果没有年份被选中,则返回
                      if (year == "") return;
                      console.log((year));
    //                获取选中年份的字段
                      var tableType = value;
                      var tableTypeText = text;
                      console.log(tableType)
    {#                   if( !tableType || !year){#}
    {#                        alert("缺少参数,必须要指年份!");#}
    {#                        return;#}
    {#                    }#}
                      var tbody=window.document.getElementById("tbody-result");
                      var tbody2=window.document.getElementById("tbody-result2");
                      $.ajax({
                          url:"year/?year="+year+"&table=" + tableType,
                          type:'GET',
                          success:function (msg) {
    {#                          反序列化#}
                              var data = eval('(' + msg + ')');
                              console.log(typeof(msg));
                              var table_data = data['detail_info'];
                              console.log(table_data)
                              var str1 = '';
                              var str2 = '';
                              if (!table_data){
                                  tbody.innerHTML='';
                                  tbody2.innerHTML='';
                                  return
                              }
                              for ( k in table_data){
                                  console.log(k)
                                  str1 += "<tr>" +
                                              "<td>"+ table_data[k]['province'] +"</td>" +
                                              "<td>"+ table_data[k]['year_total'] +"</td>" +
                                              "<td>"+ table_data[k]['month1'] +"</td>" +
                                              "<td>"+ table_data[k]['month2'] +"</td>" +
                                              "<td>"+ table_data[k]['month3'] +"</td>" +
                                              "<td>"+ table_data[k]['month4'] +"</td>" +
                                              "<td>"+ table_data[k]['month5'] +"</td>" +
                                              "<td>"+ table_data[k]['month6'] +"</td>" +
                                              "<td>"+ table_data[k]['month7'] +"</td>" +
                                              "<td>"+ table_data[k]['month8'] +"</td>" +
                                              "<td>"+ table_data[k]['month9'] +"</td>" +
                                              "<td>"+ table_data[k]['month10'] +"</td>" +
                                              "<td>"+ table_data[k]['month11'] +"</td>" +
                                              "<td>"+ table_data[k]['month12'] +"</td>" +
                                        "</tr>"
                                  str2 += "<tr>"+
                                            "<td>"+ table_data[k]['province'] +"</td>" +
                                            "<td>"+ table_data[k]['base_company_count'] +"</td>" +
                                            "<td>"+ table_data[k]['base_monitor_count'] +"</td>" +
                                            "<td>"+ table_data[k]['base_monitor_info_count'] +"</td>" +
                                          "</tr>"
                              }
                              tbody.innerHTML = str1;
                              tbody2.innerHTML = str2;
    
                          }
                      })
    
                  }
              });
    
         </script>
    
    {% endblock %}
    View Code

     4、显示效果

    选择条件:

    动态获取数据,在不重新刷新页面的情况下加载数据表单

  • 相关阅读:
    使用JFileChooser实现在指定文件夹下批量添加根据“数字型样式”或“非数字型样式”命令的文件夹
    51Nod 1376 最长递增子序列的数量 (DP+BIT)
    POJ 2728 Desert King (最优比率树)
    UVa 11280 Flying to Fredericton (DP + Dijkstra)
    UVa 11367 Full Tank? (DP + Dijkstra)
    UVa 10269 Adventure of Super Mario (Floyd + DP + BFS)
    UVaLive 4452 The Ministers' Major Mess (TwoSat)
    UVa 11294 Wedding (TwoSat)
    HDU 3247 Resource Archiver (AC自动机+BFS+状压DP)
    HDU 5957 Query on a graph (拓扑 + bfs序 + 树剖 + 线段树)
  • 原文地址:https://www.cnblogs.com/liangping/p/7645057.html
Copyright © 2020-2023  润新知