Django:(4)Django和Ajax
向服务器发送请求的途径:
1. 浏览器地址栏,默认get请求
2. form表单:
get请求;
post请求
3. a标签,默认get请求
4. Ajax:get请求;post请求
Ajax的特点(记住):
(1) 异步请求
(2)局部刷新
AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(传输的数据不只是XML,现在更多使用json数据)。
- 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
- 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
优点:
- AJAX使用Javascript技术向服务器发送异步请求
- AJAX无须刷新整个页面
基于Jquery的Ajax实现
目录结构:

urls.py
from django.contrib import admin
from django.urls import path from app01 import views urlpatterns = [
path('admin/', admin.site.urls),
path(r"index/",views.index),
path(r"test_ajax/",views.test_ajax) # ajax的路径需要有流程线(如,路由分发的路径,视图函数,页面等)
]
views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
def index(request):
return render(request,"index.html")
def test_ajax(request):
return HttpResponse("hello world")
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h2>this is Index</h2>
<button class="ajax">Ajax</button>
<p class="content"></p>
</body>
<script>
$(".ajax").click(function () {
$.ajax({
{# ajax请求的url;IP和端口没写就默认为当前的 #}
url:"/test_ajax/",
{# 请求方式;默认get #}
type:"get",
{#回调函数#}
success:function (data) {
$(".content").html(data)
}
})
})
{# 上述Ajax流程:点击button按钮,通过ajax向 特定的url发送请求;服务器返回字符串 "hello world"并传给回调函数的形参 data;回调函数决定怎么在页面上展示data #}
</script>
</html>
Ajax传递数据:通过 data:{ } 的形式 发送数据
urls.py
from django.contrib import admin
from django.urls import path from app01 import views urlpatterns = [
path('admin/', admin.site.urls),
path(r"index/",views.index),
path(r"plus/",views.plus)
]
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body> <input type="text" class="val1">+<input type="text" class="val2">=<input type="text" class="val3"> <button class="cal">计算</button> </body>
<script> $(".cal").click(function () {
$.ajax({
url:"/plus/",
type:"post",
{#ajax的input中不需要添加 name 属性,只需要 class或id 能找到它就行;但form表单需要利用 name属性去取值#}
data:{
{# input框中的值是字符串格式 #}
"val1":$(".val1").val(),
"val2":$(".val2").val()
},
success:function (data) {
$(".val3").val(data)
}
})
}) </script>
</html>
views.py
from django.shortcuts import render,HttpResponse def plus(request):
print(request.POST)
val1 = request.POST.get("val1")
val2 = request.POST.get("val2") val3 = int(val1) + int(val2) return HttpResponse(val3)
注:settings.py MIDDLEWARE 中的 'django.middleware.csrf.CsrfViewMiddleware' 需要注释掉
基于Ajax的登陆验证(跨语言的Json)
目录结构同上;settings.py 也注释掉 csrf
urls.py
from django.contrib import admin
from django.urls import path from app01 import views urlpatterns = [
path('admin/', admin.site.urls),
path(r"index/",views.index), path(r"login/",views.login)
]
views.py
from django.shortcuts import render,HttpResponse from app01.models import User def login(request):
print(request.POST)
user = request.POST.get("user")
psw = request.POST.get("psw") user_obj = User.objects.filter(name=user,psw=psw).first()
res = {"user":None,"msg":None} if user_obj: # 能在数据库中匹配出来
res["user"] = user_obj.name
else:
res["msg"] = "用户名密码错误" # 字典格式的数据类型不能直接发送,需要先转化为字符串格式
import json
# 利用json.dumps()序列化
return HttpResponse(json.dumps(res))
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body> {#form表单的action也没必要写,其实form标签也没必要;只是习惯上把form控件标签放到form中#}
<form>
用户名 <input type="text" class="user">
密码 <input type="password" class="psw">
{# 用ajax发请求时 input的type用"button",不要用"submit",否则就变成了form表单发送请求 #}
<input type="button" value="submit" class="login_btn"><span class="error"></span>
</form> </body>
<script> {# 登陆验证 #}
$(".login_btn").click(function () {
{# 把ajax内置在某个事件中 #}
$.ajax({
url:"/login/",
type:"post",
data:{
"user":$(".user").val(),
"psw":$(".psw").val()
},
success:function (data) {
console.log(data)
{# 此时data为json字符串格式 #}
console.log(typeof data) {# 此时data这个字符串交给JS去处理了;就需要用JS的反序列化方法 #}
{# 只要该语言支持json接口,它就能反解成自己支持的数据类型:python的字典会反解成JS的对象({}),python的列表会反解成JS的数组([])#}
{# JSON.parse()是JS的反序列化方法 #}
var new_data = JSON.parse(data)
console.log(new_data)
console.log(typeof new_data) if (new_data.user){
{# location.href= 表示前端跳转 #}
location.href="https://www.baidu.com"
}else {
$(".error").html(new_data.msg).css({"color":"red","margin-left":"10px"})
} }
})
}) </script>
</html>
文件上传:
请求头ContentType:
ContentType指的是消息主体的编码类型,常见的类型共有3种:
1. application/x-www-form-urlencoded:这应该是最常见的 POST 提交数据的方式了。浏览器的原生 <form> 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。请求类似于下面这样
POST http://www.example.com HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=utf-8 user=yuan&age=22
2. multipart/form-datamultipart/form-data:这又是一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 <form> 表单的 enctype 等于 multipart/form-data
3. application/json:Json格式的字符串作为请求头
基于form表单的文件上传
urls.py
from django.contrib import admin
from django.urls import path from app01 import views urlpatterns = [
path(r"file_put/",views.file_put)
]
views.py
from django.shortcuts import render,HttpResponse def file_put(request):
if request.method == "POST": # 1. 基于form表单的文件上传
print(request.POST)
# request.POST 只有在 contentType = urlencoded 时候才有数据 # 注意:上传成功的文件放在 request.FILEs 这个属性里面
print(request.FILES) # 下载所上传的文件
file_obj = request.FILES.get("avatar")
# 文件对象有一个属性 .name 表示文件名
with open(file_obj.name,"wb") as f:
for line in file_obj:
f.write(line) return HttpResponse("ok") return render(request,"file_put.html")
file_put.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head>
<body>
<h3>基于form表单的文件上传</h3> {# 注意:上传文件的form表单中要写上 enctype="multipart/form-data" #}
<form action="" method="post" enctype="multipart/form-data">
用户名 <input type="text" name="user">
{# 上传文件 input的type属性值是 "file" #}
头像 <input type="file" name="avatar">
<input type="submit"> </script>
</html>
利用Ajax上传普通数据
views.py
from django.shortcuts import render,HttpResponse def file_put(request):
if request.method == "POST": return HttpResponse("ok") return render(request,"file_put.html")
file_put.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head>
<body> <h3>基于Ajax的文件上传</h3> {# 利用Ajax上传普通数据 #}
<form action="" method="post">
用户名 <input type="text" name="user">
<input type="button" class="btn" value="Ajax">
</form> </body>
<script>
{#利用Ajax上传普通数据 #}
$(".btn").click(function () {
$.ajax({
{#url不写默认为当前路径#}
url: "",
type: "post",
{#不指定enctype,默认用application/x-www-form-urlencoded #}
data: {
a: 1,
b: 2
},
success: function (data) {
console.log(data)
}
})
})
{#不论是form表单还是Ajax都有一个默认的请求头 application/x-www-form-urlencoded #} </script>
</html>
Ajax传递Json数据
views.py
from django.shortcuts import render,HttpResponse def file_put(request):
if request.method == "POST":
# 3. Ajax传递Json数据
print("request.body",request.body) # request.body:请求报文中的请求体(请求体的源数据);
# request.body b'{"a":1,"b":2}' # 此数据可通过python的json.dumps()方法获取
print("request.POST",request.POST) # 此时 request.POST 中没有数据
# request.POST <QueryDict: {}> return HttpResponse("ok") return render(request,"file_put.html")
file_put.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head>
<body>
{#Ajax传递Json数据#}
<form action="" method="post">
用户名 <input type="text" name="user">
<input type="button" class="btn" value="Ajax">
</form>
</body>
<script> {#Ajax传递Json数据#}
$(".btn").click(function () {
$.ajax({
{#url不写默认为当前路径#}
url:"",
type:"post",
{#告诉服务器编码类型为json数据#}
contentType:"application/json",
{#然后需要用JS的方法把数据变成Json数据类型:JSON.stringify():序列化 #}
{#然后请求体中的数据就是 {"a":"1","b":"2"} 类型的json字符串 #}
data:JSON.stringify({
a:1,
b:2
}),
success:function (data) {
console.log(data)
}
})
}) </script>
</html>
基于Ajax的文件上传
views.py
from django.shortcuts import render,HttpResponse def file_put(request):
if request.method == "POST":
# 4. 基于Ajax的文件上传
print("request.body", request.body)
print("request.POST", request.POST) # request.POST <QueryDict: {'user': ['neo']}>
print(request.FILES) # <MultiValueDict: {'avatar': [<InMemoryUploadedFile: default.jpg (image/jpeg)>]}> # 下载所上传的文件
file_obj = request.FILES.get("avatar")
# file_obj = request.FILES.get("avatar")
# 文件对象有一个属性 .name 表示文件名
with open(file_obj.name,"wb") as f:
for line in file_obj:
f.write(line) return HttpResponse("ok") return render(request,"file_put.html")
file_put.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head>
<body> {# 基于Ajax的文件上传 #}
<form action="" method="post">
用户名 <input type="text" class="user">
{# 上传文件 input的type属性值是 "file" #}
头像 <input type="file" class="avatar">
<input type="button" class="btn" value="Ajax">
</form> </body>
<script> {# 基于Ajax的文件上传 #}
$(".btn").click(function () {
{#涉及到文件上传,一定要用 FormData 创建一个新的对象(formdata编码);固定格式 #}
var formdata = new FormData();
{#然后给创建的 formdata对象添加键值:append(key,value)方法 #}
formdata.append("user",$(".user").val());
formdata.append("avatar",$(".avatar")[0].files[0]);
{#$(".avatar")[0]是对应的 input 标签,DOM元素;取DOM元素中包含的文件对象: .files[0],固定语法 #} $.ajax({
{#url不写默认为当前路径#}
url:"",
type:"post",
{#传formdata的时候一定要加上 contentType:false,processData:false, 这两句代码 #}
{# contentType:false 表示不做编码处理 #}
contentType:false,
{#processData:false表示不对数据做预处理#}
processData:false,
{#把formdata赋值给data#}
data:formdata,
success:function (data) {
console.log(data)
}
})
}) </script>
</html>
Django:(4)Django和Ajax的更多相关文章
- {Django基础七之Ajax} 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解)
Django基础七之Ajax 本节目录 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解) 一 Ajax简介 ...
- Django框架 之 基于Ajax中csrf跨站请求伪造
Django框架 之 基于Ajax中csrf跨站请求伪造 ajax中csrf跨站请求伪造 方式一 1 2 3 $.ajaxSetup({ data: {csrfmiddlewaretoken: ...
- day 72 Django基础七之Ajax
Django基础七之Ajax 本节目录 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解) 六 同源策略与 ...
- day 60 Django基础七之Ajax
Django基础七之Ajax 本节目录 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解) 六 同源策 ...
- {Django基础七之Ajax} 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解)
{Django基础七之Ajax} 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解) Django基础七之 ...
- Django基础五之Ajax
Django基础五之Ajax 目录 Django基础五之Ajax 1. Ajax介绍 2. Ajax前后端传值 2.1 方法一HttpResponse直接返回 2.2 方法二使用Json格式返回 2. ...
- Django 框架 django的请求生命周期
概述 首先我们知道HTTP请求及服务端响应中传输的所有数据都是字符串,同时http请求是无状态的,可以通过session和cookie来辅助. 浏览器通过ip和端口及路由方式访问服务端. 在Djang ...
- Django settings — Django 1.6 documentation
Django settings - Django 1.6 documentation export DJANGO_SETTINGS_MODULE=mysite.settings django-admi ...
- Python之路【第二十三篇】:Django 初探--Django的开发服务器及创建数据库(笔记)
Django 初探--Django的开发服务器及创建数据库(笔记) 1.Django的开发服务器 Django框架中包含一些轻量级的web应用服务器,开发web项目时不需再对其配置服务器,Django ...
- Django 初探--Django的开发服务器及创建数据库(笔记)
1.Django的开发服务器 Django框架中包含一些轻量级的web应用服务器,开发web项目时不需再对其配置服务器,Django提供的内置服务器可以在代码修改时自动加载,从而实现网站的迅速开发. ...
随机推荐
- 积分图像的应用(一):局部标准差 分类: 图像处理 Matlab 2015-06-06 13:31 137人阅读 评论(0) 收藏
局部标准差在图像处理邻域具有广泛的应用,但是直接计算非常耗时,本文利用积分图像对局部标准差的计算进行加速. 局部标准差: 标准差定义如下(采用统计学中的定义,分母为): 其中. 为了计算图像的局部标准 ...
- shell 2 解析
---- shell 3 /home/oracle/utility/macro/call_autopurge_arch.sh Description: Call purge archive log f ...
- C++中的数学函数汇总
math.h 数学函数库,一些数学计算的公式的具体实现是放在math.h里,具体有: 1 三角函数 double sin (double); double cos (double); double t ...
- JSR-303原生支持的限制
@Null: 限制只能为null@NotNull: 限制必须不为null@AssertFalse: 限制必须为false@AssertTrue: 限制必须为true@DecimalMax(value) ...
- php安装ionCube
- 技术杂记之:vi使用入门
对于Linux的初次使用者来说,进入Linux非图形界面后,不知道怎么创建文本(甚至于在图形界面,也找不到创建文本的菜单).其实,每一个Linux的发行版本,都包含了一个最简单.也是最基础的文本编辑器 ...
- SpringSecurity的简单使用
导入SpringSecurity坐标 在web.xml中配置过滤器 编写spring-securiy配置文件 编写自定义认证提供者 用户新增时加密密码 配置页面的login和logout 获取登录用户 ...
- P1603 斯诺登的密码
题目背景 根据斯诺登事件出的一道水题 题目描述 题目描述 2013年X月X日,俄罗斯办理了斯诺登的护照,于是他混迹于一架开往委内瑞拉的飞机.但是,这件事情太不周密了,因为FBI的间谍早已获悉他的具体位 ...
- oracle DBA笔试题
Unix/Linux题目: 1.如何查看主机CPU.内存.IP和磁盘空间? cat /proc/cpuinfo cat /proc/meminfo ifconfig –a fdisk –l 2.你 ...
- Python+CGI,在Windows上快速部署Python到IIS
通过CGI,我们可以快速在Windows上部署Python 1. Windows安装IIS服务 2. 在IIS里打开“ISAPI和CGI限制”->添加,路径=python.exe的完全路径+&q ...