有時(shí)候我們想把一個(gè) list 或者 dict 傳遞給 javascript,處理后顯示到網(wǎng)頁(yè)上僧免,比如要用 js 進(jìn)行可視化的數(shù)據(jù)。
方法一:視圖函數(shù)渲染
直接在視圖函數(shù)(views.py中的函數(shù))中渲染一個(gè) list 或 dict 的內(nèi)容捏浊,和網(wǎng)頁(yè)其它部分一起顯示到網(wǎng)頁(yè)上(一次性地渲染懂衩,還是同一次請(qǐng)求)。
# ajax_test/urls.py
url(r'^home/$',views.home,name='ajax_test_home'),
#ajax_text/views.py
#coding:utf-8
from django.shortcuts import render
import json
# Create your views here.
def home(request):
#List = ['My Djano', '渲染Json到模板']
List = ['My Djano', 'Json']
Dict = {'site': 'NGS_TEST', 'author': '蘇亞男'}
return render(request, 'ajax_test/home.html',
{'List': json.dumps(List),'Dict':json.dumps(Dict)})
# ajax_test/templates/ajax_test/home.html
{% extends 'learn/base.html' %}
{% block title %}歡迎光臨ajax_test首頁(yè){% endblock %}
{% block content %}
這里是首頁(yè)金踪,歡迎光臨!<br/>
<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>
{% endblock %}
# learn/templates/learn/base.html
<!DOCTYPE html>
<html>
<head>
<title>
{% block title %}NGS{% endblock %}
</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"> </script>
</head>
注:瀏覽器調(diào)試代碼
如果您的瀏覽器支持調(diào)試靶瘸,你可以使用 console.log() 方法在瀏覽器中顯示 JavaScript 值苫亦。瀏覽器中使用 F12 來(lái)啟用調(diào)試模式, 在調(diào)試窗口中點(diǎn)擊 "Console" 菜單怨咪。
方法二:Ajax再次請(qǐng)求
一屋剑,頁(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è)上厂财。
用 Django實(shí)現(xiàn)不刷新網(wǎng)頁(yè)的情況下加載一些內(nèi)容。
由于用 jQuery 實(shí)現(xiàn) ajax 比較簡(jiǎn)單峡懈,所以我們用 jQuery庫(kù)來(lái)實(shí)現(xiàn)璃饱,也可以用原生的 javascript 實(shí)現(xiàn)。這里舉例1拓展計(jì)算a+b逮诲,舉例2傳遞一個(gè)數(shù)組或字典到網(wǎng)頁(yè)帜平,由JS處理再顯示出來(lái)。
Demo1:加載字典和列表梅鹦,JSON格式傳遞數(shù)據(jù)
# ajax_test/urls.py
url(r'^index/$',views.index,name='ajax_test_index'),
url(r'^ajax_list/$', views.ajax_list, name='ajax-list'),
url(r'^ajax_dict/$', views.ajax_dict, name='ajax-dict'),
# ajax_test/views.py
#coding:utf-8
import os
from django.shortcuts import render
from django.http import HttpResponse
import json
from django.http import JsonResponse
from suynblog import settings
# Create your views here.
def index(request):
return render(request, 'ajax_test/index.html')
def ajax_list(request):
a = range(100)
#return HttpResponse(json.dumps(a),content_type='application/json')
return JsonResponse(a, safe=False)
def ajax_dict(request):
name_dict = {'suyn': 'Love python and Django', 'Miss Su': 'I am learning Django'}
#return HttpResponse(json.dumps(name_dictm),content_type='application/json')
return JsonResponse(name_dict)
# ajax_test/templates/ajax_test/index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"> </script>
</head>
<body>
<div id="dict">Ajax 加載字典</div>
<p id="dict_result"></p>
<div id="list">Ajax 加載列表</div>
<p id="list_result"></p>
<script>
$(document).ready(function(){
// 列表 list
$('#list').click(function(){
$.getJSON('{% url 'ajax_test: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_test:ajax-dict' %}',function(ret){
//返回值 ret 在這里是一個(gè)字典
$('#dict_result').append(ret.suyn + '<br>');
// 也可以用 ret['twz']
})
})
});
</script>
</body>
</html>
Demo2:根據(jù)圖片名稱加載圖片裆甩,form請(qǐng)求
# ajax_test/urls.py
url(r'^picIndex/$',views.picIndex),
url(r'^get_pic/$', views.get_pic, name='get-pic'),
# ajax_test/views.py
#coding:utf-8
import os
from django.shortcuts import render
from django.http import HttpResponse
import json
from django.http import JsonResponse
from suynblog import settings
# Create your views here.
BASE_DIR = settings.BASE_DIR
print BASE_DIR #/root/suyn_website/suynblog
PICS = os.listdir(os.path.join(BASE_DIR, 'common_static/pics'))
print PICS #['DNA.jpg', 'desktop.jpg']
def picIndex(request):
return render(request, 'ajax_test/pics.html')
def get_pic(request):
color = request.GET.get('color')
number = request.GET.get('number')
name = '{}_{}'.format(color, number)
# 過(guò)濾出符合要求的圖片,假設(shè)是以輸入的開(kāi)頭的都返回
result_list = filter(lambda x: x.startswith(name), PICS)
print 'result_list', result_list #result_list ['red_1_2.png', 'red_11.png']
# 去掉pics.html默認(rèn)的color number的value屬性齐唆,可以自己輸入嗤栓。result_list ['red_2.jpg']
return HttpResponse(json.dumps(result_list),content_type='application/json')
# ajax_test/templates/ajax_test/pics.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"> </script>
</head>
<body>
<p>請(qǐng)輸入</p>
<form action="{% url 'ajax_test:get-pic' %}" method="get">
color: <input type="text" id="color" name="color" > <br>
number: <input type="text" id="number" name="number" > <br>
<p>result: <span id='result'></span></p>
<button type="button" id='sum'>提交</button>
</form>
<script>
$(document).ready(function(){
$("#sum").click(function(){
var color = $("#color").val();
var number = $("#number").val();
$.get("{% url 'ajax_test:get-pic' %}", {'color':color,'number':number}, function(ret){
$('#result').html('') //清空前面的結(jié)果
$.each(ret, function(index, item){
$('#result').append('![](/static/pics/'+item+')');
})
})
});
});
</script>
</body>
</html>