VS2019 開發Django(十)------JavaScript與Django的數據交互


導航:VS2019開發Django系列

 

這一篇介紹如何使用BootStrap Table這個組件來綁定渲染數據,

1)先來看一下BootStrap Table是怎么綁定數據的。

  • 通過數據屬性

    給定data-url="{% url 'test' %}",插件會自動請求這個地址的數據,然后渲染,這個地址對應的url為前幾篇演示JsonResponse的地址:http://localhost:8090/hello/test/,url的綁定規則,可以參考官方文檔,這里的test為url指定的name

    data-single-select="true",設置 true 為允許復選框僅選擇一行

    data-click-to-select="true",設置 true為在單擊行時選擇復選框或radiobox。

    data-checkbox-header="false",設置 false為隱藏標題行中的check-all復選框。

    data-field,設置你需要綁定的數據源的字段(key)

    from django.urls import path,include
    from hello import views
    
    #D:\項目\local\DjangoLazyOrders\hello\urls.py
    urlpatterns = [path('hello/',views.hello,name='hello'),
                   path('test/',views.test,name='test'),
                   path('lazy_orders_index/',views.lazy_orders_index,name='lazy_orders_index'),
                   path('<int:category_id>/category/', include([path('delete/', views.category_delete,name='category_delete'),path('edit/', views.category_edit,name='category_edit')]))]
    <div class="panel panel-info">
        <div class="panel-heading">
            <h3 class="panel-title">Test</h3>
        </div>
        <div class="panel-body">
            <table data-toggle="table"
                   data-single-select="true"
                   data-click-to-select="true"
                   data-checkbox-header="false"
                   data-url="{% url 'test' %}">
                <thead>
                    <tr>
                        <th data-field="state" data-checkbox="true"></th>
                        <th data-field="name">姓名</th>
                        <th data-field="sex">性別</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
    def test(request):
        #data = {
        #'name': 'dengwei',
        #'sex': '男'
        #}
    
        data = [{
        'name': 'dengwei',
        'sex': ''
        },{
        'name': '女帝',
        'sex': ''
        }]
        
        
        return JsonResponse(data,safe=False)

    最終渲染的效果如下圖所示:發現效果與上一篇中通過JS實現單選行的效果一樣,幾乎沒寫什么代碼,通過設置幾個屬性就達到了同樣的效果,何樂而不為?

  • 通過Javascript

    clickToSelect->data-click-to-select,所有的屬性都是在JavaScript中指定的字段都是一一對應的關系,前面添加data,單詞之間使用“-”分割

    checkboxHeader->data-checkbox-header

    singleSelect->data-single-select

    columns指定列,data指定數據源,這里要注意着色部分,這個categorys是取自Django后台傳入的數據json_categorys,后台返回的數據要直接給JavaScript使用,必須添加safe過濾器,safe過濾器的作用就是不對字符串轉義

    <div class="panel panel-info">
        <div class="panel-heading">
            <h3 class="panel-title">類別</h3>
        </div>
        <div class="panel-body">
            <div class="list-op" id="list_op">
                <button type="button" class="btn btn-default btn-sm" id="btbtn_category_add">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                </button>
                <button type="button" class="btn btn-default btn-sm" id="btbtn_category_edit">
                    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
                </button>
                <button type="button" class="btn btn-default btn-sm" id="btbtn_category_delete">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>刪除
                </button>
            </div>
            <table id="bttable_category">
            </table>
        </div>
    
    </div>
    var categorys = {{ json_categorys | safe }};
    
    $bttable_category.bootstrapTable({
        clickToSelect: true,
        checkboxHeader: false,
        singleSelect: true,
        columns: [{
            checkbox: true
        }, {
            field: 'category_id',
            title: 'ID'
        }, {
            field: 'category_name',
            title: '類別名'
        }
        ],
        data: categorys
    })
    $bttable_category.bootstrapTable('hideLoading');
    def lazy_orders_index(request):
        categorys = Category.objects.all()#查詢所有的類別
        menus = Menu.objects.all()#查詢所有的菜單
    
        json_categorys = []#定義兩個數組 用來保存model的json數據
        json_menus = []
    
        for category in categorys:
            json_categorys.append({
            "category_id":category.category_id,
             "category_name":category.category_name#遍歷實體對象 構建ViewModel的數據
             })
    
        for menu in menus:
            json_menus.append({
                "category_name":menu.category.category_name,
                "menu_name":menu.menu_name
                })
    
        context = {'json_categorys': json.dumps(json_categorys),'json_menus':json.dumps(json_menus),'categorys':categorys,'menus':menus,'year':datetime.now().year}
        return render(request,'hello/lazyorders.cshtml',context)#將數據和模板傳給render函數 渲染成html返回給客戶端

    最終渲染的效果如下圖:

    效果與上一篇演示的效果是一樣的,但是,效率就不一樣,我們可以查看網頁的源代碼,看看服務器返回的html文本有什么不一樣。

2)查看網頁的源代碼

  • 未使用BootStrap Table,可以看到服務器渲染了整個table的源代碼,還有要做效果(比如單選)等的JS代碼,於服務器與開發人員來說,耗時費力啊!

  •  使用BootStrap Table,模板里邊寫的是什么內容,返回的就是什么內容,Html不會在服務端渲染,而是到了客戶端后,通過JS渲染的界面,於服務器和開發人員而言,都是一種福利。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM