應(yīng)用一:有時(shí)候我們想把一個(gè) list 或者 dict 傳遞給 javascript,處理后顯示到網(wǎng)頁(yè)上,比如要用 js 進(jìn)行可視化的數(shù)據(jù)。
請(qǐng)注意:如果是不處理,直接顯示在網(wǎng)頁(yè)上,用Django模板就可以了。
這里講述兩種方法:
一,頁(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è)上。
二,直接在視圖函數(shù)(views.py中的函數(shù))中渲染一個(gè) list 或 dict 的內(nèi)容,和網(wǎng)頁(yè)其它部分一起顯示到網(wǎng)頁(yè)上(一次性地渲染,還是同一次請(qǐng)求)。
需要注意兩點(diǎn):1、views.py中返回的函數(shù)中的值要用 json.dumps()處理 2、在網(wǎng)頁(yè)上要加一個(gè) safe 過(guò)濾器
view.py
# -*- 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
<!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> 應(yīng)用二:不刷新網(wǎng)頁(yè)的情況下,加載一些內(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>請(qǐng)輸入兩個(gè)數(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 實(shí)現(xiàn) ajax 比較簡(jiǎn)單,所以我們用 jQuery庫(kù)來(lái)實(shí)現(xiàn).。
用了jQuery.get() 方法,并用 $(selector).html() 方法將結(jié)果顯示在頁(yè)面上,如下圖:

應(yīng)用三:傳遞數(shù)字或者字典到網(wǎng)頁(yè),由JS處理,再顯示出來(lái)
首先定義接口和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'), ]
然后就是在無(wú)刷新的情況下,把內(nèi)容加載到頁(yè)面了。
index.html
<!DOCTYPE html> <html> <body> <p>請(qǐng)輸入兩個(gè)數(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 在這里是一個(gè)列表 for (var i = ret.length - 1; i >= 0; i--) { // 把 ret 的每一項(xiàng)顯示在網(wǎng)頁(yè)上 $('#list_result').append(' ' + ret[i]) }; }) }) // 字典 dict $('#dict').click(function(){ $.getJSON("{% url 'ajax_dict' %}",function(ret){ //返回值 ret 在這里是一個(gè)字典 $('#dict_result').append(ret.a + '<br>'); // 也可以用 ret['twz'] }) }) }); </script> </body> </html> 注意:getJSON中的寫的對(duì)應(yīng)網(wǎng)址,用 urls.py 中的 name 來(lái)獲取是一個(gè)更好的方法!標(biāo)簽:{% url 'name' %}
這樣做最大的好處就是在修改 urls.py 中的網(wǎng)址后,不用改模板中對(duì)應(yīng)的網(wǎng)址。
如果是一個(gè)復(fù)雜的字典或者列表,如:
person_info_dict = [ {"name":"xiaoming", "age":20}, {"name":"tuweizhong", "age":24}, {"name":"xiaoli", "age":33}, ] 這樣我們遍歷列表的時(shí)候,每次遍歷得到一個(gè)字典,再用字典的方法去處理,當(dāng)然有更簡(jiǎn)單的遍歷方法:
用 $.each() 方法代替 for 循環(huán),html 代碼(jquery)
$.getJSON('ajax_url_to_json', function(ret) { $.each(ret, function(i,item){ // i 為索引,item為遍歷值 }); }); 補(bǔ)充:如果 ret 是一個(gè)字典,$.each 的參數(shù)有所不同,詳見:http://api.jquery.com/jquery.each/
$.getJSON('ajax-get-a-dict', function(ret) { $.each(ret, function(key, value){ // key 為字典的 key,value 為對(duì)應(yīng)的值 }); }); 以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選