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

Posted lplucky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;width: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>" +
                                        "前端上传图片的三种方法

Django动态表与AJAX

Python下利用Selenium获取动态页面数据

前端数据修改的两种方式

web前端面试,被问到ajax如果获取到一个页面的内容,如何渲染到页面呢

markdown [Django与Ajax实现网页动态数据显示]#学习笔记#Web编程#Django