應(yīng)用一:有時(shí)候我們想把一個(gè) list 或者 dict 傳遞給 javascript,處理后顯示到網(wǎng)頁(yè)上,比如要用 js 進(jìn)行可視化的數(shù)據(jù)。
請(qǐng)注意:如果是不處理,直接顯示在網(wǎng)頁(yè)上,用Django模板就可以了。
這里講述兩種方法:
一,頁(yè)面加載完成后,在頁(yè)面上操作,在頁(yè)面上通過(guò) ajax 方法得到新的數(shù)據(jù)(再向服務(wù)器發(fā)送一次請(qǐng)求)并顯示在網(wǎng)頁(yè)上,這種情況適用于頁(yè)面不刷新的情況下,動(dòng)態(tài)加載一些內(nèi)容。比如用戶輸入一個(gè)值或者點(diǎn)擊某個(gè)地方,動(dòng)態(tài)地把相應(yīng)內(nèi)容顯示在網(wǎng)頁(yè)上。
二,直接在視圖函數(shù)(views.py中的函數(shù))中渲染一個(gè) list 或 dict 的內(nèi)容,和網(wǎng)頁(yè)其它部分一起顯示到網(wǎng)頁(yè)上(一次性地渲染,還是同一次請(qǐng)求)。
需要注意兩點(diǎn):1、views.py中返回的函數(shù)中的值要用 json.dumps()處理 2、在網(wǎng)頁(yè)上要加一個(gè) safe 過(guò)濾器
view.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.shortcuts import render def home(request): List = ['自強(qiáng)學(xué)堂', '渲染Json到模板'] Dict = {'site': '自強(qiáng)學(xué)堂', 'author': '涂偉忠'} return render(request, 'home.html', { 'List': json.dumps(List), 'Dict': json.dumps(Dict) }) home.html
<!DOCTYPE html> <html> <head> <title>歡迎光臨 自強(qiáng)學(xué)堂!</title> <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body> <div id="list"> 學(xué)習(xí) </div> <div id='dict'></div> <script type="text/javascript"> //列表 var List = {{ List|safe }}; //下面的代碼把List的每一部分放到頭部和尾部 $('#list').prepend(List[0]); $('#list').append(List[1]); console.log('--- 遍歷 List 方法 1 ---') for(i in List){ console.log(i);// i為索引 } console.log('--- 遍歷 List 方法 2 ---') for (var i = List.length - 1; i >= 0; i--) { // 鼠標(biāo)右鍵,審核元素,選擇 console 可以看到輸入的值。 console.log(List[i]); }; console.log('--- 同時(shí)遍歷索引和內(nèi)容,使用 jQuery.each() 方法 ---') $.each(List, function(index, item){ console.log(index); console.log(item); }); // 字典 var Dict = {{ Dict|safe }}; console.log("--- 兩種字典的取值方式 ---") console.log(Dict['site']); console.log(Dict.author); console.log("--- 遍歷字典 ---"); for(i in Dict) { console.log(i + Dict[i]);//注意,此處 i 為鍵值 } </script> </body> </html> 應(yīng)用二:不刷新網(wǎng)頁(yè)的情況下,加載一些內(nèi)容
view.py
#coding:utf-8 from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def get(request): return render(request, 'oneapp/get.html') def add(request): a = request.GET.get('a', 0) b = request.GET.get('b', 0) c = int(a) + int(b) return HttpResponse(str(c))
新聞熱點(diǎn)
疑難解答
圖片精選