十二.通過bootstrap的modal.js來完成刪除功能

Modal.js是bootstrap的一個js插件,以彈出對話框的形式出現,具有最小和最實用的功能集。具體使用方法可以參見http://v3.bootcss.com/javascript/

 

在這次實例中,還會包括一些Jquery及AJAX的方法,通過AJAX來根據刪除結果對頁面進行不刷新的更改。

 

1.      新建modal.html,通過這個文件來創建一個適用於絕大多數情況的modal框,可以在不同的地方調用

Modal.html:

<!-- Modal -->
<!-- Modal的id爲modal_form-->
 <div class="modal fade" id="modal_form" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
   <div class="modal-dialog" role="document">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
         <h4 class="modal-title" id="myModalLabel">刪除任務</h4>
       </div>
         <!--Form的id爲myForm-->
         <form id="myForm" method="POST" >{% csrf_token %}
       <div class="modal-body">
        <!--存放content內容-->
       </div>
       <div class="modal-footer">
         <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
         <button type="submit" class="btn btn-primary" >確認</button>
       </div>
        </form>
     </div>
   </div>
 </div>

2.      建立modal_js.html,來操控modal.html,例如通過res_list.html來獲取標題及提示內容,並把它們賦值給modal.html。同時,也用AJAX來滿足myForm的提交與響應

Modal_js.html:

<script type="text/javascript">
         //如果href中有modal_form這個id的,那麼點擊後會調用如下函數
        $("[href='#modal_form']").click(function(){
              //定義modal_id,確保每個按鈕所產生的id不一樣,否則將會是最先遇到的那個
            var modal_id = "#" + $(this).attr('id');
     //填充modal的各種元素
    $('.modal-title').text($(modal_id).attr('title'));
    $('.modal-body').text($(modal_id).attr('content'));
     //form提交
    $('#myForm').on('submit', function(e){
         //防止冒泡
         e.preventDefault();
         //提交到相應的rel上
      $.post($(modal_id).attr('rel'),
         $(this).serialize(),
         function(data, status, xhr) {
             //網頁返回正常且刪除操作成功
            if (status == 'success' && data == 'success') {
                 $('.modal-body').text('操作成功');
                 $('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">返回</button>');
            //提交失敗的操作
             } else {
                 $('.modal-body').text('操作失敗,請重新選擇條目,或聯繫管理人員');
             $('.modal-footer').html('<button type="button" class="btn btn-default" data-dismiss="modal">返回</button>');
         }
         });
    });
});
        //當modal頁面消失後,重新將頁面刷新
        $(function () { $('#modal_form').on('hide.bs.modal', function () {
        window.location.reload();})
   });
</script>


3.      在res_list中,修改刪除按鈕的鏈接,併爲每個刪除按鈕分配一個modal_id,避免混淆。通過include來引用modal.html:

res_list.html:

<!—代碼省略-->
<!--刪除信息按鈕,爲每個刪除按鈕設置一個id,並將content和title傳遞給modal-->
 <a id="modal_button_{{ item.id }}" class="red" href="#modal_form"
   data-toggle="modal" rel="{% url 'delete' table item.id %}" content="確認刪除該條目麼?"
   title="刪除信息">
    <i class="ace-icon fa fa-trash-o bigger-130"></i>
</a>
<!—代碼省略-->
   <li>
  <a id="modal_button_{{ item.id }}" class="red" href="#modal_form"
                   data-toggle="modal" rel="{% url 'delete' table item.id %}" content="確認刪除該條目麼?"
                   title="刪除信息">
<span class="red">
   <i class="ace-icon fa fa-trash-o bigger-120"></i>
</span>
                            </a>
                        </li>
<!—代碼省略-->
<!--引入modal.html-->
{% include 'modal.html' %}

<!—代碼省略-->

{% block page_javascript %}
     {% include 'modal_js.html' %}
<!--datatable的專用js-->
          //代碼省略
{% endblock %}

4.    增加url選項

<pre name="code" class="python">#刪除數據
url(r'^delete/(?P<table>\w+)/(?P<pk>\d+)/$', echo.views.delete, name='delete'),


5.  在views.py中增加刪除的處理函數

# -*- coding: UTF-8 -*-
from .models import Node,Line,Device
from forms import NodeForm,LineForm,DeviceForm
from django.shortcuts import render, redirect, get_object_or_404
from django.db import IntegrityError
from django.http import JsonResponse

#刪除操作
def delete(request, table ,pk):
    #選擇相應的表格
    if table == 'line':
        #通過id值獲取相應表格的實例,有值則返回,無值則拋出異常
        table_ins = get_object_or_404(Line, pk=pk)

    if table == 'node':
        table_ins = get_object_or_404(Node, pk=pk)

    if table == 'device':
        table_ins = get_object_or_404(Device, pk=pk)

    #接收通過AJAX提交過來的POST
    if request.method == 'POST':
        #刪除該條目
        try:
            table_ins.delete()
            #刪除成功,則data信息爲success
            data = 'success'
        except IntegrityError:
            #如因外鍵問題,或其他問題,刪除失敗,則報error
            data = 'error'
        #將最後的data值傳遞至JS頁面,進行後續處理
        return JsonResponse(data)

6.      訪問網址,先建立一個廣州的節點信息,可以正常刪除




7.      刪除上海數據中心的節點信息,發現操作失敗,原因在於,在上海數據中心上已經建立了相關設備信息和線路信息,而在model中的外鍵配置爲

node = models.ForeignKey(Node, on_delete=models.PROTECT)

即在刪除模式爲保護模式,在未將所有和該節點有關的信息刪除之前,該節點不能被刪除,當然具體需求可以根據業務需要而來。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章