美文网首页django 学习量化编程django
Django 通过Ajax局部刷新更新Table

Django 通过Ajax局部刷新更新Table

作者: 童乐瑶 | 来源:发表于2017-03-16 13:04 被阅读729次

    在Python Django框架中,通过Ajax方式向后台提交查询请求,返回数据,前台局部刷新Table的方式完成数据条件查询。

    Post提交方式与Get方式存在略微的区别,因为Post是修改添加操作,涉及到数据的读写,而Get更多只是读取,明显Post的权限要大的多,所以安全方面限制也要更多,提供CSRFtoken是为了防止跨域攻击,因为现在很容易用第三方工具构造出Post以及Get请求。


    ** settings.py中添加CsrfViewMiddleware支持**

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',# csrf
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.security.SecurityMiddleware',
    )
    

    view.py中对响应的处理函数

    def query(request):
        env = request.POST.get('envir_name')
        pro = request.POST.get('project_name')
    
        cursor = connection.cursor()
        data = []
        data_list = []
        cursor.execute('select * from table_name where Hostname like "' + env + '%"  and Hostname like "%' + pro + '%"')
        for row in cursor.fetchall():
            data_list.append(row)
            dict_row = {}
            dict_row['id'] = row[0]
            dict_row['col_1'] = row[1]
            dict_row['col_2'] = row[2]
            dict_row['col_3'] = row[3]
            dict_row['col_4'] = row[4]
            dict_row['col_5'] = row[5]
            dict_row['col_6'] = row[6]
            dict_row['col_7'] = row[7]
            dict_row['col_8'] = row[8]
            dict_row['col_9'] = row[9]
            dict_row['col_10'] = row[10]
            dict_row['col_11'] = row[11]
            dict_row['col_12'] = row[12]
            dict_row['col_13'] = row[13]
            dict_row['col_14'] = row[14]
            data.append(dict_row)
    
        response = HttpResponse()
        response['Content-Type'] = "text/javascript"
        response.write(json.dumps({'rows':data, 'total': len(data)}))
        return response
    

    ** HTML 构造form表单:**

    <div class="widget-body">
         <form class="form-inline" role="form" id='formquery'>
                <div class="form-group">
                     <input type="text" class="form-control" id="envir_name" placeholder="环境名称">
                </div>
                <div class="form-group">
                      <input type="text" class="form-control" id="project_name" placeholder="项目名称">
                </div>
                <button type="submit" class="btn btn-default">确定</button>
           </form>
           <table class="table table-bordered table-striped table-condensed flip-content" id="expandabledatatable">
                 <thead class="flip-content bordered-darkorange">
                   <tr>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th>
                       <th>列*****</th></tr>
                </thead>
                <tbody id="tbody">
                      {% for record in lists %}
                           <tr>
                               <td><a href="#">{{ record.col_1}}</a></td>
                                <td>{{ record.col_2}}</td>
                                <td>{{ record.col_3}}</td>
                                <td>{{ record.col_4}}</td>
                                <td>{{ record.col_5}}</td>
                                <td>{{ record.col_6}}</td>
                                <td>{{ record.col_7}}</td>
                                <td>{{ record.col_8}}</td>
                                <td>{{ record.col_9}}</td>
                                <td>{{ record.col_10}}</td>
                                <td>{{ record.col_11}}</td>
                                <td>{{ record.col_12}}</td>
                                <td>{{ record.col_13}}</td>
                                <td>{{ record.col_14}}</td>
                            </tr>
                        {% endfor %}
                </tbody>
          </table>
      </div>
     </div>
    </div>
    
    

    ** JavaScript 通过ajax发送请求,动态更新table:**

    <script>$.ajaxSetup({headers: {"X-CSRFToken": '{{ csrf_token }}'}});</script>
    <script type="text/javascript">
            $(document).ready(function () {
                $('#formquery').submit(function () {
                    var Envir = $("#envir_name").val();
                    var Project = $("#project_name").val();
                    $.ajax({
                        type: "POST",
                        data: {envir_name: Envir, project_name: Project},
                        url: "{% url 'query' %}",
                        cache: false,
                        dataType: "json",
                        success: function (result) {
                            var total = result.total;
                            var rows = result.rows;
                            var table = document.getElementById("expandabledatatable");
                            var infos = document.getElementById("tbody");
                            $('#tbody').empty(); //清空tbody内容
                            // 生成新的table数据元素并添加到table中
                            for (var i = 0; i < rows.length; i++) {
                                var tr = document.createElement("tr");
                                var td1 = document.createElement("td");
                                var td2 = document.createElement("td");
                                var td3 = document.createElement("td");
                                var td4 = document.createElement("td");
                                var td5 = document.createElement("td");
                                var td15 = document.createElement("td");
                                var td6 = document.createElement("td");
                                var td7 = document.createElement("td");
                                var td8 = document.createElement("td");
                                var td9 = document.createElement("td");
                                var td10 = document.createElement("td");
                                var td11 = document.createElement("td");
                                var td12 = document.createElement("td");
                                var td13 = document.createElement("td");
                                td1.innerHTML = rows[i].col_1;
                                td2.innerHTML = rows[i].col_2;
                                td3.innerHTML = rows[i].col_3;
                                td4.innerHTML = rows[i].col_4;
                                td5.innerHTML = rows[i].col_5;
                                td6.innerHTML = rows[i].col_6;
                                td7.innerHTML = rows[i].col_7;
                                td8.innerHTML = rows[i].col_8;
                                td9.innerHTML = rows[i].col_9;
                                td10.innerHTML = rows[i].col_10;
                                td11.innerHTML = rows[i].col_11;
                                td12.innerHTML = rows[i].col_12;
                                td13.innerHTML = rows[i].col_13;
                                td14.innerHTML = rows[i].col_14;
    
                                tr.appendChild(td1);
                                tr.appendChild(td2);
                                tr.appendChild(td3);
                                tr.appendChild(td4);
                                tr.appendChild(td5);
                                tr.appendChild(td6);
                                tr.appendChild(td7);
                                tr.appendChild(td8);
                                tr.appendChild(td9);
                                tr.appendChild(td10);
                                tr.appendChild(td11);
                                tr.appendChild(td12);
                                tr.appendChild(td13);
                                tr.appendChild(td14);
                                infos.appendChild(tr);
                            }
                             $("#table_id tbody").append(infos);
    
                        },
                        error: function () {
                            alert("false");
                        }
                    });
                    return false;
                });
            });
        </script>
    

    ** 浏览器中条件查询结果**

    ** 附录**
    Q1:表单方式的POST提交HTTP 403问题?
    A1:Django的Cross Site Request Forgery protection机制。这个机制是为了保护不受csrf攻击。具体解决办法是:
    (1)在settings.py文件中找到 MIDDLEWARE_CLASSES,在其中加入一个中间件:'django.middleware.csrf.CsrfViewMiddleware' ;
    (2)如果你是用jQuery来处理ajax的话,发送请求前加上<script>$.ajaxSetup({headers: {"X-CSRFToken": '{{ csrf_token }}'}});</script>。或者把它放在一个独立的js文件中,在html页面中都引入。注意这个js文件必须在jquery的js文件引入之后,再引入。
    这样就可以解决表单方式的POST提交HTTP 403问题了,正常用ajax与Django通信了。

    相关文章

      网友评论

      本文标题:Django 通过Ajax局部刷新更新Table

      本文链接:https://www.haomeiwen.com/subject/dnadnttx.html