美文网首页
Django高级(二):JavaScript Ajax

Django高级(二):JavaScript Ajax

作者: 宇辰星君 | 来源:发表于2017-04-06 16:45 被阅读32次

https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

有时候我们想把一个 list 或者 dict 传递给 javascript,处理后显示到网页上,比如要用 js 进行可视化的数据。

方法一:视图函数渲染

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

# 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首页{% endblock %}
{% block content %}
这里是首页,欢迎光临!<br/>
<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>
{% 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>

注:浏览器调试代码
如果您的浏览器支持调试,你可以使用 console.log() 方法在浏览器中显示 JavaScript 值。浏览器中使用 F12 来启用调试模式, 在调试窗口中点击 "Console" 菜单。

方法二:Ajax再次请求

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

用 Django实现不刷新网页的情况下加载一些内容。
由于用 jQuery 实现 ajax 比较简单,所以我们用 jQuery库来实现,也可以用原生的 javascript 实现。这里举例1拓展计算a+b,举例2传递一个数组或字典到网页,由JS处理再显示出来。

Demo1:加载字典和列表,JSON格式传递数据

# 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 在这里是一个列表
                for (var i = ret.length - 1; i >= 0; i--) {
                    // 把 ret 的每一项显示在网页上
                    $('#list_result').append(' ' + ret[i])
                };
            })
        })

        // 字典 dict
        $('#dict').click(function(){
            $.getJSON('{% url 'ajax_test:ajax-dict' %}',function(ret){
                //返回值 ret 在这里是一个字典
                $('#dict_result').append(ret.suyn + '<br>');
                // 也可以用 ret['twz']
            })
        })
    });
</script>
</body>
</html>

Demo2:根据图片名称加载图片,form请求

# 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)

    # 过滤出符合要求的图片,假设是以输入的开头的都返回
    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默认的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>请输入</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('') //清空前面的结果
                $.each(ret, function(index, item){
                    $('#result').append('![](/static/pics/'+item+')');
                })
            })
        });
    });
</script>

</body>
</html>

相关文章

网友评论

      本文标题:Django高级(二):JavaScript Ajax

      本文链接:https://www.haomeiwen.com/subject/ezyqattx.html