django中ajax介绍及应用

django中ajax应用

一、Ajax介绍

  Ajax(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML)。

  • 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
  • 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。

  Ajax除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)。因此使用ajax的主要特点有如下几点:(1)Ajax使用Javascript技术向服务器发送异步请求;(2)Ajax无须刷新整个页面;(3)因为服务器响应内容不再是整个页面,而是页面中的局部,所以Ajax性能高。在django入门项目中我们已经简单的介绍了一下ajax应用。下面我们将做详细介绍。

二、ajax实现方式

  具体实现方式实例如下:

html文件部分: object是js中的对象,可以理解类似于python中的字典。

ajax常用参数:
url:"/url/",
type: "post/get",
data:data,
1) ps:data参数中的键值对,如果值不为字符串,需要将其转换成字符串类型,例如:
data:{"i1":$("#i1").val(),"i2":$("#i2").val(),"hehe": JSON.stringify([1, 2, 3])}, 是个js对象
2) 自动收集表单中的数据(找到每个字段,#regForm为form表单的id) urlencoded:?i1=1&i2=2;
var data = $("#regForm").serialize(); // 自动携带csrf_token
dataType: "JSON", // 规定前端返回值 ,服务器返回的json字符串自动会反序列成前端js对象,不会再手动反序列化JSON.parse()了
我们先来看看dataType属性到底是个什么东西,
1.dataType值如果为'json',jquery就会把后端返回的字符串尝试通过JSON.parse()尝试解析为js对象。
2.dataType值如果为'text',结果弹出框直接显示后台返回的json字符串。
3.dataType值如果为'html',结果弹出框直接显示后台返回的json字符串。
当代码中加上dataType:“json” ,这个属性后,我们再次看到返回结果就是java对象了,不需要我们去手动的解析json字符串

header中Content-Type="application/json",此时的data必须是json字符串,也告诉django后端是json数据,需要反序列化

img

后端函数部分:

img

传递参数

data:传递简单参数时,在django后端中request.POST获取,而传递复杂数据(字典/列表中嵌套列表),要在request.body获取原始bytes类型数据。

img

三、$.Ajax的参数

1、contentType类型一 

  上述实例中是我们对ajax的基本使用,也是ajax中参数contentType的默认使用方式,他决定了发送信息至服务器时内容编码的类型。现将此参数的默认使用方式总结如下:

data: 当前ajax请求要携带的数据,是一个object对象,ajax方法就会默认地把它编码成某种格式(urlencoded:?a=1&b=2)发送给服务端;此外,ajax默认以get方式发送请求。
contentType:"application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型。用来指明当前请求的数据编码格式;urlencoded:?a=1&b=2

2、contentType类型二  

  上述这种默认参数形式,data中的csrf跨站请求伪造键值对会被中间件自动识别,contentType参数还有如下一种形式,介绍如下:

contentType:"application/json",即向服务器发送一个json字符串。注意:contentType:"application/json"一旦设定,data必须是json字符串,不能是json对象

html文件部分:

img

后端函数部分:

img

  上述通过headers参数发送csrf跨站请求伪造其实共有两种方式获取那个值,分别总结如下:

方式一:  headers:{"X-CSRFToken":$("[name='csrfmiddlewaretoken']").val()}
方式二:  headers:{"X-CSRFToken":$.cookie("csrftoken")}, #其中方式二需引用jquery.cookie.js文件,如:<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
                           

四、上传文件

1、form表单上传

  如下实例以注册页面为例,form表单提交的时候需要在form中设置enctype="multipart/form-data"属性,使得form中数据和file文件以不同的方式发送值后端,后端通过不同的方法取出相应的数据进行处理。

html文件:

<form class="form-horizontal" style="margin-top: 20px" action="{{ request.get_full_path }}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-sm-offset-4 col-sm-8">
<h2>注册页面</h2>
<span style="color: red"> {{ error_msg }}</span>
</div>
<div class="form-group">
<label for="username" class="col-sm-2 control-label col-sm-offset-2">姓名</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="username" placeholder="数字或字母组成,不能包含特殊字符" name="username">
</div>
</div>
<div class="form-group">
<label for="userpswd1" class="col-sm-2 control-label col-sm-offset-2">密码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="userpswd1" placeholder="密码长度至少为8位字符组成" name="userpswd1">
</div>
</div>
<div class="form-group">
<label for="userpswd2" class="col-sm-2 control-label col-sm-offset-2">确认密码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="userpswd1" placeholder="密码长度至少为8位字符组成" name="userpswd2">
</div>
</div>
<div class="form-group">
<label for="img_file" class="col-sm-2 control-label col-sm-offset-2">上传头像</label>
<div class="col-sm-4">
<input type="file" id="img_file" name="img_file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<input type="submit" class="btn btn-success btn-lg btn-block" value="确定">
</div>
</div>
</form>

后端处理函数:

import osfrom day78.settings import BASE_DIR
def formreg(request):
if request.method=="POST":
print(request.POST)
user=request.POST.get("username")
userpswd1=request.POST.get("userpswd1")
userpswd2=request.POST.get("userpswd2")
print(user,userpswd1,userpswd2)
if userpswd1==userpswd2:
User.objects.create_user(username=user,password=userpswd1)
print(request.FILES)
file_obj=request.FILES.get("img_file") #获取文件对象
file_name=file_obj.name #获取文件名字
path = os.path.join(BASE_DIR, "app01", "static", file_name)
with open(path,"wb") as f:
for line in file_obj:
f.write(line)
return HttpResponse("注册成功")
return render(request,"formreg.html")

2、ajax上传文件

html文件部分:

<form class="form-horizontal" style="margin-top: 20px">
{% csrf_token %}
<div class="col-sm-offset-4 col-sm-8">
<h2>注册页面</h2>
<span style="color: red" class="error_msg"></span>
</div>
<div class="form-group">
<label for="username" class="col-sm-2 control-label col-sm-offset-2">姓名</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="username" placeholder="数字或字母组成,不能包含特殊字符" name="username">
</div>
</div>
<div class="form-group">
<label for="userpswd1" class="col-sm-2 control-label col-sm-offset-2">密码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="userpswd1" placeholder="密码长度至少为8位字符组成" name="userpswd1">
</div>
</div>
<div class="form-group">
<label for="userpswd2" class="col-sm-2 control-label col-sm-offset-2">确认密码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="userpswd2" placeholder="密码长度至少为8位字符组成" name="userpswd2">
</div>
</div>
<div class="form-group">
<label for="img_file" class="col-sm-2 control-label col-sm-offset-2">上传头像</label>
<div class="col-sm-4">
<input type="file" id="img_file" name="img_file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<input type="button" class="btn btn-success btn-lg btn-block" value="确定" id="ensure">
</div>
</div>
</form>
<div style="margin-left: 220px">
<img src="/static/3.jpg" alt="" class="img-rounded">
<img src="/static/3.jpg" alt="" class="img-circle">
<img src="/static/3.jpg" alt="" class="img-thumbnail">
</div>
</div>
<script src="/static/jquery-3.2.1.min.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
<script>
$("#ensure").click(function () {
var $formData=new FormData();
$formData.append("username",$("#username").val());
$formData.append("userpswd1",$("#userpswd1").val());
$formData.append("userpswd2",$("#userpswd2").val());
$formData.append("img_file",$("#img_file")[0].files[0]);
$.ajax({
url:"/ajaxreg/",
type:"POST",
data:$formData,
contentType:false,
processData:false,
headers:{"X-CSRFToken":$('[name="csrfmiddlewaretoken"]').val()},
success:function (data) {
$(".error_msg").text(data)
}
})
})
</script>

后端处理函数:

  与form提交处理的方式一样,如下:

import os
from day78.settings import BASE_DIR
def ajaxreg(request):
if request.is_ajax():
username = request.POST.get("username")
userpswd1 = request.POST.get("userpswd1")
userpswd2 = request.POST.get("userpswd2")
print(username, userpswd1, userpswd2)
if userpswd1 == userpswd2:
User.objects.create_user(username=username, password=userpswd1)
print(request.FILES)
file_obj = request.FILES.get("img_file") # 获取文件对象
file_name = file_obj.name # 获取文件名字
path = os.path.join(BASE_DIR, "app01", "static", file_name)
with open(path, "wb") as f:
for line in file_obj:
f.write(line)
return HttpResponse("注册成功")
else:
return HttpResponse("注册失败")
return render(request,"ajaxreg.html")

转自 https://www.cnblogs.com/seven-007/p/8034043.html

ajax学习链接:https://www.w3school.com.cn/jquery/ajax_ajax.asp

posted @   hanfe1  阅读(369)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示