Django傳遞資料給JS
有時候我們想把一個 list 或 dict等 JSON物件 傳到網頁的 javascript,用 JS 進行處理,比如用 js 將資料視覺化顯示到網頁上。
請注意:如果不需要處理,直接顯示到網頁上,用Django模板就可以了,請看前面的教程。
這裡講述兩種方法:
一,頁面載入完成後,在頁面上操作,在頁面上通過 ajax 方法得到新的資料(再向伺服器傳送一次請求)並顯示在網頁上,這種情況適用於頁面不重新整理的情況下,動態載入一些內容。比如使用者輸入一個值或者點選某個地方,動態地把相應內容顯示在網頁上。
二,直接在檢視函式(views.py中的函式)中將 JSON物件 和網頁其它內容一起傳遞到Django模板(一次性地渲染,還是同一次請求
請看下面的示例:
views.py
1 2 3 4 5 6 7 |
render(request, 'home.html' , { 'List' : List }) |
home.html 中的一部分
1 2 3 4 |
|
需要注意的是,我們如果直接這麼做,傳遞到 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 |
|
home.html 只給出了 js 核心部分:
1 2 3 4 |
|
如果你對 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 |
|