請(qǐng)注意:如果是不處理,直接顯示在網(wǎng)頁(yè)上,用Django模板就可以了,請(qǐng)看前面的教程。
這里講述兩種方法:
一,頁(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è)上。
這種請(qǐng)問(wèn)詳見(jiàn) Django Ajax 一節(jié)的內(nèi)容。
二,直接在視圖函數(shù)(views.py中的函數(shù))中渲染一個(gè) list 或 dict 的內(nèi)容,和網(wǎng)頁(yè)其它部分一起顯示到網(wǎng)頁(yè)上(一次性地渲染,還是同一次請(qǐng)求)。
請(qǐng)看下面的示例:
views.py
1 2 3 4 5 6 | from __future__ import unicode_literals from django.shortcuts import render def home(request): List = [ '自強(qiáng)學(xué)堂' , '渲染Json到模板' ] return render(request, 'home.html' , { 'List' : List }) |
home.html 中的一部分
1 2 3 4 | < script type = "text/javascript" > var List = {{ List }}; alert(List); </ script > |
需要注意的是,我們?nèi)绻苯舆@么做,傳遞到 js 的時(shí)候,網(wǎng)頁(yè)的內(nèi)容會(huì)被轉(zhuǎn)義,得到的格式會(huì)報(bào)錯(cuò)。
訪問(wèn)時(shí)會(huì)得到 Uncaught SyntaxError: Unexpected token ILLEGAL
需要注意兩點(diǎn):
1. views.py中返回的函數(shù)中的值要用 json.dumps()處理
2. 在網(wǎng)頁(yè)上要加一個(gè) safe 過(guò)濾器。
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # -*- 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 只給出了 js 核心部分:
1 2 3 4 | //列表 var List = {{ List|safe }}; //字典 var Dict = {{ Dict|safe }}; |
如果你對(duì) js 比較熟悉,至此為止,下面的不用于看了,如果不太熟悉,可以參考下面的更詳細(xì)的代碼。
html 完全代碼及完整代碼下載(最后面):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <!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 > |
聯(lián)系客服