Django与Ajax
ajax 概念
1 概念: AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)
2 异步:请求发出去,不会卡在这,可以干其他事
3 局部刷新:js的dom操作,使页面局部刷新
4 基本上web页面都有很多ajax请求
写ajax跟后端交互
1 使用原生js写ajax请求(没有人用)
-第一:麻烦
-第二:区分浏览器,需要做浏览器兼容
2 现在主流做法(现成有人封装好了,jquery,axios..)
-以jquery为例讲(前后端混合jquery方法)
-axios为例(前后端分离axios方法)
ajax计算器
后端
def ajax_test(request):
return render(request,'ajax_test.html')
def sum(request):
import time
time.sleep(2)
a1=int(request.GET.get('a1'))
a2=int(request.GET.get('a2'))
return HttpResponse(a1+a2)
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<input type="text" id="a1"> + <input type="text" id="a2">=<input type="text" id="sum">
<button id="btn_submit">计算</button>
</body>
<script>
$('#btn_submit').click(function () {
var a1 = $('#a1').val()
var a2 = $('#a2').val()
// 发送ajax请求,计算,返回结果
$.ajax({
url: '/sum/', //ajax请求的地址
method: 'get',//请求方式
data: {'a1': a1, 'a2': a2}, //携带参数
success:function (data) { //服务端成功返回会回调,执行匿名函数
console.log(data)
$('#sum').val(data)
}
})
})
</script>
</html>
ajax发送其他请求
1
-如果在form表单中,写button和input是submit类型,会触发form表单的提交
-如果不想触发:
-不写在form表单中
-使用input,类型是button
2
-后端响应格式如果是:html/text格式,ajax接收到数据后需要自己转成对象
-后端响应格式是:json,ajax接收到数据后会自动转成对象
-总结:后端返回数据,统一都用JsonResponse、
3
-如果使用了ajax,后端就不要返回rediret,render,HttpResponse
-直接返回JsonResponse
登录功能前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p> 用户名:<input type="text" id="id_name"></p>
<p> 密码:<input type="password" id="id_password"></p>
<button id="id_btn">提交</button> <span class="error" style="color: red"></span>
</body>
<script>
$('#id_btn').click(function () {
$.ajax({
url: '/login/',
method: 'post',
data: {username: $('#id_name').val(), password: $('#id_password').val()},
success: function (data) {
//res=JSON.parse(data)
//console.log(data)
//console.log(res)
// data 现在是对象类型
if(data.status==100){
//登录成功,重定向到百度,前端重定向
location.href='http://www.baidu.com'
//location.href='/index/'
}else {
//登录失败
//$('.error').html(data.msg).css({'color':'red'})
$('.error').html(data.msg)
}
},
error: function (data) {
console.log(data)
}
})
})
</script>
</html>
登录功能后端
from django.shortcuts import render,redirect,HttpResponse
from django.http import JsonResponse
# Create your views here.
from app01 import models
import json
def login(request):
if request.method=='GET':
return render(request,'login.html')
# elif request.method=='POST':
elif request.is_ajax():
response={'status':100,'msg':None}
name=request.POST.get('username')
password=request.POST.get('password')
user=models.User.objects.filter(name=name,password=password).first()
if user:
# 用户名和密码都对了
# return redirect('') 出错
response['msg']="登录成功"
else:
response['status']=101
response['msg'] = "用户名或密码错误"
# return HttpResponse(json.dumps(response))
return JsonResponse(response)
# return redirect('http://www.baidu.com')
# return render(request,'login.html')
登录路由
url(r'^login/', views.login),
登录功能模型类
from django.db import models
# Create your models here.
class User(models.Model):
name=models.CharField(max_length=32)
password=models.CharField(max_length=32)
上传文件(ajax和form两种方式)
1 http --post--请求,有编码格式,主流有三种
-urlencoded :默认的----》从request.POST取提交的数据
-form-data :上传文件的----》从request.POST取提交的数据,request.FILES中取文件
-json :ajax发送json格式数据-----》request.POST取不出数据了
2 使用ajax和form表单,默认都是urlencoded格式
3 如果上传文件:form表单指定格式,ajax要使用Formdata对象
4 如果编码方式是urlencoded格式,放到body体中数据格式如下
username=lqz&password=123
5 如果是formdata编码格式,body体中是:两部分,数据和文件
6 如果是json格式,body体中的格式是:就是json格式字符串
-注意:注意:注意:如果这种格式,request.POST取不到值了
form表单上传文件
<h1>form表单上传文件</h1>
<form action="" method="post" enctype="multipart/form-data">
<p>用户名:<input type="text" name="name"></p>
<p>文件:<input type="file" name="myfile"></p>
<input type="submit" value="提交">
</form>
ajax 上传文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>ajax上传文件</h1>
<p>用户名:<input type="text" id="id_name"></p>
<p>文件:<input type="file" id="id_myfile"></p>
<button id="id_btn">提交</button>
</body>
<script>
$('#id_btn').click(function () {
//如果要上传文件,需要借助于一个js的FormData对象
var formdata = new FormData() //实例化得到一个FormData对象
formdata.append('name', $('#id_name').val()) //追加了一个name对应填入的值
//能追加文件
var file = $('#id_myfile')[0].files[0]
formdata.append('myfile', file)
$.ajax({
url: 'file_upload',
method: 'post',
//上传文件,一定要注意如下两行
processData: false, //不预处理数据,
contentType: false, //不指定编码格式,使用formdata对象的默认编码就是formdata格式
data: formdata,
success: function (data) {
console.log(data)
}
})
})
</script>
</html>
后端
def file_upload(request):
if request.method=='GET':
return render(request,'file_upload.html')
else:
name=request.POST.get('name')
myfile=request.FILES.get('myfile')
print(type(myfile)) # 查看类型
from django.core.files.uploadedfile import InMemoryUploadedFile
with open(myfile.name,'wb') as f:
for line in myfile:
f.write(line)
return HttpResponse('上传成功')
路由
url(r'^file_upload/', views.file_upload),
ajax上传json格式
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>ajax提交json格式</h1>
<p>用户名: <input type="text" id="id_name"></p>
<p>密码: <input type="password" id="id_password"></p>
<button id="id_button">提交</button>
</body>
<script>
$('#id_button').click(function () {
$.ajax({
url: '/ajax_json/',
method: 'post',
contentType: 'application/json', //指定编码格式
data: JSON.stringify({name:$('#id_name').val(),password:$('#id_password').val()}), //json格式字符串
success: function (data) {
console.log(data)
}
})
})
</script>
</html>
后端
# 装饰器
def json_paser(func):
def inner(request,*args,**kwargs)
if request.method == 'POST':
try:
request.data=json.loads(request.body)
execpt Exception as e:
request.data=request.POST
res=func(request,*args,**kwargs)
return res
return inner
@json_pase
def ajax_json(request):
if request.method=='GET':
return render(request,'ajax_json.html')
else:
print(request.data)
return HttpResponse('ok')
def ajax_json(request):
if request.method=='GET':
return render(request,'ajax_json.html')
else:
# json格式,从POST中取不出来
name=request.POST.get('name')
print(type(request.POST))
# from django.http.request import QueryDict
print(name)
# 在body体中,b格式
request.data=json.loads(request.body)
name=request.data.get('name')
password=request.data.get('password')
print(name)
print(password)
return HttpResponse('ok')

浙公网安备 33010602011771号