脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Django与JS交互的示例代码

Django与JS交互的示例代码

2020-12-03 00:51pNull Python

本篇文章主要介绍了Django与JS交互的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

应用一:有时候我们想把一个 list 或者 dict 传递给 javascript,处理后显示到网页上,比如要用 js 进行可视化的数据。
请注意:如果是不处理,直接显示在网页上,用Django模板就可以了。

这里讲述两种方法:

一,页面加载完成后,在页面上操作,在页面上通过 ajax 方法得到新的数据(再向服务器发送一次请求)并显示在网页上,这种情况适用于页面不刷新的情况下,动态加载一些内容。比如用户输入一个值或者点击某个地方,动态地把相应内容显示在网页上。

二,直接在视图函数(views.py中的函数)中渲染一个 list 或 dict 的内容,和网页其它部分一起显示到网页上(一次性地渲染,还是同一次请求)。

需要注意两点:1、views.py中返回的函数中的值要用 json.dumps()处理   2、在网页上要加一个 safe 过滤器

view.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

?
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>

应用二:不刷新网页的情况下,加载一些内容

view.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#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

?
1
2
3
4
5
6
7
8
9
10
11
12
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

?
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
<!DOCTYPE html>
<html>
<body>
<p>请输入两个数字</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 实现 ajax 比较简单,所以我们用 jQuery库来实现.。

用了jQuery.get() 方法,并用 $(selector).html() 方法将结果显示在页面上,如下图:

Django与JS交互的示例代码

应用三:传递数字或者字典到网页,由JS处理,再显示出来

首先定义接口和URL

views.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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

?
1
2
3
4
5
6
7
8
9
10
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'),
]

然后就是在无刷新的情况下,把内容加载到页面了。

index.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
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<body>
<p>请输入两个数字</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 的每一项显示在网页上
    $('#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中的写的对应网址,用 urls.py 中的 name 来获取是一个更好的方法!标签:{% url 'name' %}

这样做最大的好处就是在修改 urls.py 中的网址后,不用改模板中对应的网址。

如果是一个复杂的字典或者列表,如:

?
1
2
3
4
5
person_info_dict = [
 {"name":"xiaoming", "age":20},
 {"name":"tuweizhong", "age":24},
 {"name":"xiaoli", "age":33},
]

这样我们遍历列表的时候,每次遍历得到一个字典,再用字典的方法去处理,当然有更简单的遍历方法:

用 $.each() 方法代替 for 循环,html 代码(jquery)

?
1
2
3
4
5
$.getJSON('ajax_url_to_json', function(ret) {
 $.each(ret, function(i,item){
  // i 为索引,item为遍历值
 });
});

补充:如果 ret 是一个字典,$.each 的参数有所不同,详见:http://api.jquery.com/jquery.each/

?
1
2
3
4
5
$.getJSON('ajax-get-a-dict', function(ret) {
 $.each(ret, function(key, value){
  // key 为字典的 key,value 为对应的值
 });
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/u011138533/article/details/72629728

延伸 · 阅读

精彩推荐