Django與JS交互的示例代碼
應(yīng)用一:有時候我們想把一個 list 或者 dict 傳遞給 javascript,處理后顯示到網(wǎng)頁上,比如要用 js 進行可視化的數(shù)據(jù)。
請注意:如果是不處理,直接顯示在網(wǎng)頁上,用Django模板就可以了。
這里講述兩種方法:
一,頁面加載完成后,在頁面上操作,在頁面上通過 ajax 方法得到新的數(shù)據(jù)(再向服務(wù)器發(fā)送一次請求)并顯示在網(wǎng)頁上,這種情況適用于頁面不刷新的情況下,動態(tài)加載一些內(nèi)容。比如用戶輸入一個值或者點擊某個地方,動態(tài)地把相應(yīng)內(nèi)容顯示在網(wǎng)頁上。
二,直接在視圖函數(shù)(views.py中的函數(shù))中渲染一個 list 或 dict 的內(nèi)容,和網(wǎng)頁其它部分一起顯示到網(wǎng)頁上(一次性地渲染,還是同一次請求)。
需要注意兩點:1、views.py中返回的函數(shù)中的值要用 json.dumps()處理 2、在網(wǎng)頁上要加一個 safe 過濾器
view.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.shortcuts import render
def home(request):
List = ['自強學(xué)堂', '渲染Json到模板']
Dict = {'site': '自強學(xué)堂', 'author': '涂偉忠'}
return render(request, 'home.html', {
'List': json.dumps(List),
'Dict': json.dumps(Dict)
})
home.html
<!DOCTYPE html>
<html>
<head>
<title>歡迎光臨 自強學(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--) {
// 鼠標右鍵,審核元素,選擇 console 可以看到輸入的值。
console.log(List[i]);
};
console.log('--- 同時遍歷索引和內(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)頁的情況下,加載一些內(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))
urls.py
from django.conf.urls import url, include from django.contrib import admin from OneApp import views as oneapp_views urlpatterns = [ url(r'^admin/', admin.site.urls), #url(r'^$', oneapp_views.index), url(r'^oneapp/index/', oneapp_views.index, name='index'), url(r'^oneapp/home/', oneapp_views.home, name='home'), url(r'^oneapp/get/', oneapp_views.get, name='get'), url(r'^oneapp/add/', oneapp_views.add, name='add'), ]
get.html
<!DOCTYPE html>
<html>
<body>
<p>請輸入兩個數(shù)字</p>
<form action="/oneapp/add/" method="get">
a: <input type="text" id="a" name="a"> <br>
b: <input type="text" id="b" name="b"> <br>
<p>result: <span id='result'></span></p>
<button type="button" id='sum'>提交</button>
</form>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sum").click(function(){
var a = $("#a").val();
var b = $("#b").val();
$.get("/oneapp/add/",{'a':a,'b':b}, function(ret){
$('#result').html(ret)
})
});
});
</script>
</body>
</html>
由于用 jQuery 實現(xiàn) ajax 比較簡單,所以我們用 jQuery庫來實現(xiàn).。
用了jQuery.get() 方法,并用 $(selector).html() 方法將結(jié)果顯示在頁面上,如下圖:

應(yīng)用三:傳遞數(shù)字或者字典到網(wǎng)頁,由JS處理,再顯示出來
首先定義接口和URL
views.py
#coding:utf-8
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import json
# Create your views here.
def ajax_list(request):
a = range(100)
#return HttpResponse(json.dump(a), content_type='application/json')
return JsonResponse(a, safe=False)
def ajax_dict(request):
name_dict = {'a': 1, 'b': 2}
#return HttpResponse(json.dump(name_dict), content_type='application/json')
return JsonResponse(name_dict)
urls.py
urlpatterns = [ url(r'^admin/', admin.site.urls), #url(r'^$', oneapp_views.index), url(r'^oneapp/index/', oneapp_views.index, name='index'), url(r'^oneapp/home/', oneapp_views.home, name='home'), url(r'^oneapp/get/', oneapp_views.get, name='get'), url(r'^oneapp/add/', oneapp_views.add, name='add'), url(r'^oneapp/ajax_list/', oneapp_views.ajax_list, name='ajax_list'), url(r'^oneapp/ajax_dict/', oneapp_views.ajax_dict, name='ajax_dict'), ]
然后就是在無刷新的情況下,把內(nèi)容加載到頁面了。
index.html
<!DOCTYPE html>
<html>
<body>
<p>請輸入兩個數(shù)字</p>
<form action="/add/" method="get">
a: <input type="text" id="a" name="a"> <br>
b: <input type="text" id="b" name="b"> <br>
<p>result: <span id='result'></span></p>
<button type="button" id='sum'>提交</button>
</form>
<div id="dict">Ajax 加載字典</div>
<p id="dict_result"></p>
<div id="list">Ajax 加載列表</div>
<p id="list_result"></p>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// 求和 a + b
$("#sum").click(function(){
var a = $("#a").val();
var b = $("#b").val();
$.get("{% url 'add' %}",{'a':a,'b':b}, function(ret){
$('#result').html(ret);
})
});
// 列表 list
$('#list').click(function(){
$.getJSON("{% url 'ajax_list' %}",function(ret){
//返回值 ret 在這里是一個列表
for (var i = ret.length - 1; i >= 0; i--) {
// 把 ret 的每一項顯示在網(wǎng)頁上
$('#list_result').append(' ' + ret[i])
};
})
})
// 字典 dict
$('#dict').click(function(){
$.getJSON("{% url 'ajax_dict' %}",function(ret){
//返回值 ret 在這里是一個字典
$('#dict_result').append(ret.a + '<br>');
// 也可以用 ret['twz']
})
})
});
</script>
</body>
</html>
注意:getJSON中的寫的對應(yīng)網(wǎng)址,用 urls.py 中的 name 來獲取是一個更好的方法!標簽:{% url 'name' %}
這樣做最大的好處就是在修改 urls.py 中的網(wǎng)址后,不用改模板中對應(yīng)的網(wǎng)址。
如果是一個復(fù)雜的字典或者列表,如:
person_info_dict = [
{"name":"xiaoming", "age":20},
{"name":"tuweizhong", "age":24},
{"name":"xiaoli", "age":33},
]
這樣我們遍歷列表的時候,每次遍歷得到一個字典,再用字典的方法去處理,當然有更簡單的遍歷方法:
用 $.each() 方法代替 for 循環(huán),html 代碼(jquery)
$.getJSON('ajax_url_to_json', function(ret) {
$.each(ret, function(i,item){
// i 為索引,item為遍歷值
});
});
補充:如果 ret 是一個字典,$.each 的參數(shù)有所不同,詳見:http://api.jquery.com/jquery.each/
$.getJSON('ajax-get-a-dict', function(ret) {
$.each(ret, function(key, value){
// key 為字典的 key,value 為對應(yīng)的值
});
});
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
PyQt5實現(xiàn)QLineEdit正則表達式輸入驗證器
這篇文章主要介紹了PyQt5實現(xiàn)QLineEdit正則表達式輸入驗證器,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
樹莓派4B+opencv4+python 打開攝像頭的實現(xiàn)方法
這篇文章主要介紹了樹莓派4B+opencv4+python 打開攝像頭的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
對Keras中predict()方法和predict_classes()方法的區(qū)別說明
這篇文章主要介紹了對Keras中predict()方法和predict_classes()方法的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python 如何利用argparse解析命令行參數(shù)
這篇文章主要介紹了python 利用argparse解析命令行參數(shù)的步驟,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-09-09
python 實現(xiàn)非極大值抑制算法(Non-maximum suppression, NMS)
這篇文章主要介紹了python 如何實現(xiàn)非極大值抑制算法(Non-maximum suppression, NMS),幫助大家更好的進行機器學(xué)習(xí),感興趣的朋友可以了解下2020-10-10
Python Web框架Pylons中使用MongoDB的例子
這篇文章主要介紹了Python Web框架Pylons中使用MongoDB 的例子,大家參考使用2013-12-12
Python學(xué)習(xí)之循環(huán)方法詳解
循環(huán)是有著周而復(fù)始的運動或變化的規(guī)律;在 Python 中,循環(huán)的操作也叫做 遍歷。與現(xiàn)實中一樣,Python 中也同樣存在著無限循環(huán)的方法與有限循環(huán)的方法。本文將通過示例詳細講解Python中的循環(huán)方法,需要的可以參考一下2022-03-03

