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提供的内置服务器可以在代码修改时自动加载,从而实现网站的迅速开发. ...
随机推荐
- [转]访问 OData 服务 (WCF Data Services)
本文转自:http://msdn.microsoft.com/zh-SG/library/dd728283(v=vs.103) WCF 数据服务 支持开放式数据协议 (OData) 将数据作为包含可通 ...
- 8.JAVA-向上转型、向下转型
父子对象之间的转换分为了向上转型和向下转型,它们区别如下: 向上转型 : 通过子类对象(小范围)实例化父类对象(大范围),这种属于自动转换 向下转型 : 通过父类对象(大范围)实例化子类对象(小范围) ...
- mysql之修改字符编码
目录 统一修改字段编码 修改单个字段编码 修改表字符编码 统一修改字段编码: alter table `tablename` convert to character set utf8; 修改表字符编 ...
- Wamp搭建的服务器登录的时候出现Access denied for user 'hello'@'localhost' (using password: YES)
想用自己电脑做一个服务器,然后就选择了Wamp,本来一切顺利,可是到登录的时候却出现了问题,出现了 Access denied for user 'hello'@'localhost' (using ...
- Node.js——获取文件上传进度
https://juejin.im/post/5a77a46cf265da4e78327552?utm_medium=fe&utm_source=weixinqun
- Functor、Applicative 和 Monad x
首先,我们来看一下 Functor typeclass 的定义: 1 2 class Functor f where fmap :: (a -> b) -> f a -> f b F ...
- Swift 关键字 inout - 让值类型以引用方式传递
两种参数传递方式 值类型 传递的是参数的一个副本,这样在调用参数的过程中不会影响原始数据. 引用类型 把参数本身引用(内存地址)传递过去,在调用的过程会影响原始数据. 在 Swift 众多数据类型中, ...
- js 或jquery定义方法时,参数不固定是怎么实现的
//①不定义接受参数的方式来接受参数(arguments) function getparams(){ //利用arguments来接受参数,arguments表示参数集合, //里面存放的调用这个方 ...
- java正则表达式进阶运用20181023
直接上代码. package org.jimmy.autotranslate20181022.test; import java.util.regex.Matcher; import java.uti ...
- 第2节 mapreduce深入学习:7、MapReduce的规约过程combiner
第2节 mapreduce深入学习:7.MapReduce的规约过程combiner 每一个 map 都可能会产生大量的本地输出,Combiner 的作用就是对 map 端的输出先做一次合并,以减少在 ...