转载Django 传递数据给JSON

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

 

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

请看下面的示例:

views.py

1
2
3
4
5
6
from __future__ import unicode_literals
from django.shortcuts import render
 
def home(request):
    List = [ '自强学堂' , '渲染Json到模板' ]
    return render(request, 'home.html' , { 'List' : List })

home.html 中的一部分

1
2
3
4
< script type = "text/javascript" >
    var List = {{ List }};
    alert(List);
</ script >

需要注意的是,我们如果直接这么做,传递到 js 的时候,网页的内容会被转义,得到的格式会报错。

访问时会得到 Uncaught SyntaxError: Unexpected token ILLEGAL

 

需要注意两点:

1. views.py中返回的函数中的值要用 json.dumps()处理

2. 在网页上要加一个 safe 过滤器。

 

views.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 只给出了 js 核心部分:

1
2
3
4
//列表
var List = {{ List|safe }};
//字典
var Dict = {{ Dict|safe }};

如果你对 js 比较熟悉,至此为止,下面的不用于看了,如果不太熟悉,可以参考下面的更详细的代码。

 

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 >

转载于:https://www.cnblogs.com/weiming-cheng/p/5291183.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值