1. 程式人生 > >Django傳遞資料給JS

Django傳遞資料給JS

有時候我們想把一個 list 或 dict等 JSON物件 傳到網頁的 javascript,用 JS 進行處理,比如用 js 將資料視覺化顯示到網頁上。

請注意:如果不需要處理,直接顯示到網頁上,用Django模板就可以了,請看前面的教程。

這裡講述兩種方法

一,頁面載入完成後,在頁面上操作,在頁面上通過 ajax 方法得到新的資料(再向伺服器傳送一次請求)並顯示在網頁上,這種情況適用於頁面不重新整理的情況下,動態載入一些內容。比如使用者輸入一個值或者點選某個地方,動態地把相應內容顯示在網頁上。

二,直接在檢視函式(views.py中的函式)中將 JSON物件 和網頁其它內容一起傳遞到Django模板(一次性地渲染,還是同一次請求

)。

請看下面的示例:

views.py

1

2

3

4

5

6

7

from __future__ import unicode_literals

from django.shortcuts import render

 

 

def home(request):

    List = ['自強學堂''渲染Json到模板']

    return

 render(request, 'home.html', {'List'List})

home.html 中的一部分

1

2

3

4

<script type="text/javascript">

    var List = {{ List }};

    alert(List);

</script>

需要注意的是,我們如果直接這麼做,傳遞到 js 的時候,網頁的內容會被轉義,得到的格式會報錯。

訪問時會得到 Uncaught SyntaxError: Unexpected token ILLEGAL

 

需要注意兩點:

1. 檢視函式中的字典或列表要用 json.dumps()處理。

2. 在模板上要加 safe 過濾器。

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 = ['自強學堂''渲染Json到模板']

    Dict = {'site''自強學堂''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 }};

如果你對 js 比較熟悉,到此為止,後面的不用看了。

如果不太熟悉,可以參考下面的更詳細的程式碼。

 

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>歡迎光臨 自強學堂!</title>

<script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>

</head>

<body>

<div id="list"> 學習 </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--) {

        // 滑鼠右鍵,稽核元素,選擇 console 可以看到輸入的值。

        console.log(List[i]);

    };

 

    console.log('--- 同時遍歷索引和內容,使用 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>