Django傳遞數據給JS
把一個list或者dict傳遞給javascript,處理后顯示到網頁,比如要用js進行可視化的數據。 這里講述兩種方法。
一.也買那加載完成后,在頁面上操作,在頁面通過ajax請求得到新的數據(再向服務器發送一次請求)並顯示在頁面上,這種情況適用於頁面不刷新的情況,動態加載一些內容。
1 views.py
2 from __future__ import unicode_literals
3 from django.shortcuts import render
4
5 def home(request):
6 List = ['北京尚學堂', '渲染Json到模板']
7 return render(request, 'home.html', {'List': List})
8
9 home.html 中的一部分
10
11 <script type="text/javascript">
12 var List = {{ List }};
13 alert(List);
14 </script>
需要注意的是,我們如果直接這么做,傳遞到 js 的時候,網頁的內容會被轉義,得到的格式會報錯。
訪問時會得到 Uncaught SyntaxError: Unexpected token ILLEGAL
需要注意兩點:
-
views.py中返回的函數中的值要用 json.dumps()處理
-
在網頁上要加一個 safe 過濾器。
views.py
1 from __future__ import unicode_literals
2 import json
3 from django.shortcuts import render
4
5 def home(request):
6 List = ['北京尚學堂', '渲染Json到模板']
7 Dict = {'site': '北京尚學堂', 'author': '尚小堂'}
8 return render(request, 'home.html', {
9 'List': json.dumps(List), # json.dumps()處理
10 'Dict': json.dumps(Dict) # json.dumps()處理
11 })
html.html只給出js部分:
1 <script type="text/javascript">
2 //列表
3 var List = {{ List|safe }};
4 //下面的代碼把List的每一部分放到頭部和尾部
5 $('#list').prepend(List[0]);
6 $('#list').append(List[1]);
7
8 console.log('--- 遍歷 List 方法 一 ---')
9 for(i in List){
10 console.log(i);// i為索引
11 }
12
13 console.log('--- 遍歷 List 方法 二 ---')
14 for (var i = List.length - 1; i >= 0; i--) {
15 // 鼠標右鍵,審核元素,選擇 console 可以看到輸入的值。
16 console.log(List[i]);
17 };
18
19 console.log('--- 同時遍歷索引和內容,使用 jQuery.each() 方法 ---')
20 $.each(List, function(index, item){
21 console.log(index);
22 console.log(item);
23 });
24
25 // 字典
26 var Dict = {{ Dict|safe }};
27 console.log("--- 2種字典的取值方式 ---")
28 console.log(Dict['site']);
29 console.log(Dict.author);
30 console.log("--- 遍歷字典 ---");
31 for(i in Dict) {
32 console.log(i + Dict[i]);//注意,此處 i 為鍵值
33 }
34 </script>
Django Ajax 有時候頁面需要在不刷新的情況下載入一些內容。
例子:在不刷新的情況下顯示計算結果到頁面上
1 <html>
2 <body>
3 <p>請輸入兩數字</p>
4 <form action="/add/" method="get">
5 a: <input type="text" id="a" name="a"> <br>
6 b: <input type="text" id="b" name="b"> <br>
7 <p>result: <span id='result'></span></p>
8 <button type="button" id='sum'>提交</button>
9 </form>
10 <script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
11 <script>
12 $(document).ready(function(){
13 $("#sum").click(function(){
14 var a = $("#a").val();
15 var b = $("#b").val();
16
17 $.get("/add/",{'a':a,'b':b}, function(ret){
18 $('#result').html(ret)
19 })
20 });
21 });
22 </script>
23 </body>
24 </html>
更復雜的例子,傳遞一個書在或者字典,由js處理,再顯示出來。
1 from django.http import JsonResponse
2
3 def ajax_list(request):
4 a = range(100)
5 return JsonResponse(a, safe=False)
6
7 def ajax_dict(request):
8 name_dict = {'twz': 'Love python and Django', 'zqxt': 'I am teaching Django'}
