Django 从后台往前台传递数据时有多种方法可以实现。

最简单的后台是这样的:

from django.shortcuts import render

def main_page(request):
return render(request, 'index.html')

这个就是返回index.html的内容,但是如果要带一些数据一起传给前台的话,该怎么办呢?

view >> HTML

这里是这样:后台传递一些数据给html,直接渲染在网页上,不会有什么复杂的数据处理(如果前台要处理数据,那么就传数据给JS处理)

Django 代码:

from django.shortcuts import render

def main_page(request):
data = [1,2,3,4]
return render(request, 'index.html', {'data': data})

html使用 {{ }} 来获取数据

<div>{{ data }}</div>

可以对可迭代的数据进行迭代:

{% for item in data%}
<p>{{ item }}</p>
{% endfor %}

该方法可以传递各种数据类型,包括list,dict等等。
而且除了 {% for %} 以外还可以进行if判断,大小比较等等。具体的用法读者可以自行搜索。

view >> JavaScript

如果数据不传给html用,要传给js用,那么按照上文的方式写会有错误。
需要注意两点:

  1. views.py中返回的函数中的值要用 json.dumps() 处理
  2. 在网页上要加一个 safe 过滤器。

代码:
views.py

# -*- coding: utf-8 -*-

import json
from django.shortcuts import render def main_page(request):
list = ['view', 'Json', 'JS']
return render(request, 'index.html', {
'List': json.dumps(list),
})

JavaScript部分:

var List = {{ List|safe }};

JavaScript Ajax 动态刷新页面

步骤1:后台数据通过 JSON 序列化成字符串

注意:1、json是1个字符串

2、通过json.dumps('xxx') 序列化成 1个字符串的 '字典对象'

views.py

def ajax(request):
if request.method=='POST':
print(request.POST)
data={'status':0,'msg':'请求成功','data':[11,22,33,44]}
return HttpResponse(json.dumps(data))
else:
return render(request,'ajax.html')

此时tempates 中ajax.html 代码

此时浏览器返回的数据

步骤2:前台取出后台序列化的字符串

方法1:正则表达式 (不推荐)

方法2:jQuery.parseJSON() ,需要import json
转换成1个JQuery可识别的字典(对象)   通过 对象. xxx 取值  (推荐)

views.py序列化:return HttpResponse(json.dumps(data))

ajax.html 取值:var obj=jQuery.parseJSON(arg)

console.log(obj.status)

修改后的tempates 中ajax.html 代码

<script type='text/javascript'>
function DoAjax(){
var temp=$('#na').val()
$.ajax({
url:'/ajax/', //url相当于 form 中的 action
type:'POST', //type相当于form 中的 method
data:{dat:temp}, // data:传人的数据 dat为任意设置的内容,相当于模版中的{author:lee}
dataType:'json',
success:function(arg){ //成功执行 console.log() 函数 arg 为HttpResponse 返回的值
var obj=jQuery.parseJSON(arg) //转化成JS识别的对象
console.log(obj) //打印obj
console.log(arg) //json.dumps(data) 序列化后的数据
console.log(obj.status) //取json.dumps(data)字典的值status
console.log(obj.msg)
console.log(obj.data)
console.log('request.POST 提交成功')
},
error:function(){ //失败
console.log('失败')
}
});
}
</script>

此时前台浏览器 显示数据

方法3:content_type='application/json'

views.py 序列化:return HttpResponse(json.dumps(data),content_type='application/json')

浏览器F12有变色提示

或:HttpResponse(json.dumps(data),content_type='type/json')   浏览器F12无变色提示

ajax.html 取值 arg.xxx

方法4:使用JsonRespon 包 (最简单)  前台通过 arg.xxx 取值

views.py 序列化: return JsonResponse(data)

ajax.html 取值:arg.xxx

区别:HttpResponse 需要dumps 
          JsonResponse 不需要dumps

views.py

from django.shortcuts import render
from django.http import JsonResponse
def ajax(request):
if request.method=='POST':
print(request.POST)
data={'status':0,'msg':'请求成功','data':[11,22,33,44]} #假如传人的数据为一字典
#return HttpResponse(json.dumps(data)) #原来写法,需要dumps
return JsonResponse(data) #后来写法
else:
return render(request,'ajax.html')

templates 中的 ajax.html

<script type='text/javascript'>
function DoAjax(){
var temp=$('#na').val()
$.ajax({
url:'/ajax/', //url相当于 form 中的 action
type:'POST', //type相当于form 中的 method
data:{dat:temp}, // data:传人的数据 dat为任意设置的内容,相当于模版中的{author:lee}
dataType:'json',
success:function(arg){ //成功执行 console.log() 函数 arg 为HttpResponse 返回的值
var obj=jQuery.parseJSON(arg) //转化成JS识别的对象
console.log(obj) //打印obj
console.log(arg) //json.dumps(data) 序列化后的数据
console.log(obj.status) //取json.dumps(data)字典的值status
console.log(obj.msg)
console.log(obj.data)
console.log('request.POST 提交成功')
},
error:function(){ //失败
console.log('失败')
}
});
}
</script>

Django-前后台的数据交互的更多相关文章

  1. Django与JS交互的示例代码-django js 获取 python 字典-Django 前后台的数据传递

    Django与JS交互的示例代码 Django 前后台的数据传递 https://www.cnblogs.com/xibuhaohao/p/10192052.html 应用一:有时候我们想把一个 li ...

  2. Python Django 前后端数据交互 之 后端向前端发送数据

    Django 前后台的数据传递 严正声明:作者:psklf出处: http://www.cnblogs.com/psklf/archive/2016/05/30/5542612.html欢迎转载,但未 ...

  3. Django 前后台的数据传递示列

    Django 前后台的数据传递的方法 Django 从后台往前台传递数据时有多种方法可以实现. 最简单的后台是这样的: ? 1 2 3 4 from django.shortcuts import r ...

  4. django 前后台传递数据

    前几天,我们完成了用django orm对数据进行操作.接下来,我们要把数据从后台放到前台. 1.用get方式传值 get:就是在URL拼接字符串,在后台,用request.get方式取 2.用pos ...

  5. Python Django 前后端数据交互 之 HttpRequest、HttpResponse、render、redirect

    在使用三神装的时候,首先当然是得要导入它们: from django.shortcuts import HttpResponse, render, redirect   一.HttpRequest捕获 ...

  6. Django 前后台的数据传递

    Django 从后台往前台传递数据时有多种方法可以实现. 最简单的后台是这样的: from django.shortcuts import render def main_page(request): ...

  7. Python Django 前后端数据交互 之 前端向后端发送数据

    Python Django 之 前端向后端发送数据

  8. Python Django 前后端数据交互 之 HTTP协议下GET与POST的区别

    99%的人都理解错了HTTP中GET与POST的区别(转自知乎)   作者:Larry链接:https://zhuanlan.zhihu.com/p/22536382来源:知乎著作权归作者所有.商业转 ...

  9. Asp.net--Ajax前后台数据交互

    转自:http://www.cnblogs.com/guolebin7/archive/2011/02/22/1961737.html 代码由前后台两部分组成: 前台:(新建一个Default.asp ...

  10. 玩转Web之Json(二)----jquery easy ui + Ajax +Json+SQL实现前后台数据交互

    最近在学Json,在网上也找过一些资料,觉得有点乱,在这里,我以easy ui的登录界面为例来说一下怎样用Json实现前后台的数据交互 使用Json,首先需要导入一些jar包,这些资源可以在网上下载到 ...

随机推荐

  1. 洛谷P2680 运输计划——树上差分

    题目:https://www.luogu.org/problemnew/show/P2680 久违地1A了好高兴啊! 首先,要最大值最小,很容易想到二分: 判断当前的 mid 是否可行,需要看看有没有 ...

  2. 解决juqery easyui combobox只能选择问题

    1.首先设定框为 combobox样式,该字段值为了进行值的显示 <tr class="odd_row"> <td class="TableLabel_ ...

  3. Mysql建表出现1005错误

    转自:http://blog.sina.com.cn/s/blog_757807f30100vz23.html 当在创建一个表时提示1005错误无法创建时,注意检查一下几点: 1.当此表有外键时,检查 ...

  4. rspec

    require 'rails_helper' RSpec.describe Jira, '#set_jira_jlist' do it "this sentence is after it& ...

  5. PHP cURL使用小结

    cURL简介 cURL是什么? cURL(Client URL Library Functions)由 Daniel Stenberg 创建的libcurl库,官方定义为:curl is a comm ...

  6. 安装Git(转载)

    转自:http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/00137396287703 ...

  7. 运行Android Studio总是未发现设备

    1.未发现虚拟机设备

  8. bzoj 1754: [Usaco2005 qua]Bull Math【高精乘法】

    高精乘法板子 然而WA了两次也是没救了 #include<iostream> #include<cstdio> #include<cstring> using na ...

  9. 10.11NOIP模拟题(2)

    /* string水过 */ #include<bits/stdc++.h> #define N 1001 using namespace std; int n,x,y,m,pre; st ...

  10. [Swift通天遁地]一、超级工具-(15)使用SCLAlertView制作强大的Alert警告窗口和Input编辑窗口

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...