django之Ajax
1. 向服务器发送请求的途径
1.浏览器地址,默认get请求
2.form表单:
get请求
post请求
3.a标签,默认get请求
4.Ajax请求
特点:
1.异步请求
2.局部刷新
2. Ajex简介
AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)。
同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)
优点:
AJAX使用Javascript技术向服务器发送异步请求
AJAX无须刷新整个页面
Ajax的简单实现、计算求值、登陆验证
index.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>index</title> </head> <body><h2>This is index!</h2><button class="Ajax">Ajex</button> <p class="content"></p><hr> <input type="text" id="num1"> + <input type="text" id="num2"> = <input type="text" id="ret"> <button class="cal">计算</button><hr><form> <!-- form都可以不用,但一般来说还是把表单标签放到form里面 -->用户名 <input type="text" id="user">密码 <input type="password" id="pwd"><input type="button" value="submit" class="login_btn"> <!-- 不能用submit,用submit就是form表单发请求了,不是ajax --><span class="error"></span> </form><script src="/static/jquery-3.3.1.js"></script><script>// 发送Ajax请求 $(".Ajax").click(function () {// 发送Ajax请求 $.ajax({url: '/test_ajax/', // 请求url type: 'get', // 或post data: {a: 1, b: 2},success: function (data) { // 回调函数:某个时间完成之后再去执行的函数 $(".content").text(data)}})});// Ajax计算求值 $('.cal').click(function () {let num1 = $('#num1').val();let num2 = $('#num2').val();$.ajax({url: '/cal/',type: 'post',data: {'n1': num1,'n2': num2,},success: function (data) { // 请求结果交给success函数 $('#ret').val(data);}})});// 登陆验证 $('.login_btn').click(function () {let user = $('#user').val();let pwd = $('#pwd').val();$.ajax({url: "/login/",type: 'post',data: {"username": user,"pwd": pwd,},success: function (data) {console.log(data); // json字符串 let parsed_data = JSON.parse(data); // 反序列化成 object类型 {}。 如果传的是列表就反序列化成数组类型if (parsed_data.user) {location.href = 'https://www.baidu.com'} else {$('.error').html(parsed_data.msg).css({'color':'red','margin-left':'10px'});}}})});</script> </body> </html>
views.py
from django.shortcuts import render, HttpResponse # Create your views here.from app01.models import User import jsondef index(request):return render(request, 'index.html')def test_ajax(request):print(request.GET)return HttpResponse('hello edward')def cal(request):n1 = int(request.POST.get('n1'))n2 = int(request.POST.get('n2'))ret = n1 + n2return HttpResponse(ret)def login(request):username = request.POST.get('username')pwd = request.POST.get('pwd')user = User.objects.filter(username=username, pwd=pwd).first()res = {'user': None, 'msg': None}if user:res['user'] = user.usernameelse:res['msg'] = 'username or password wrong!'return HttpResponse(json.dumps(res))
基于form表单的文件上传
html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>file put</title> </head> <body> <form action="" method="post" enctype="multipart/form-data">用户名 <input type="text" name="user">头像 <input type="file" name="avatar"><input type="submit"> </form> </body>
views.py
def file_put(request):if request.method == 'POST':print(request.POST)print(request.FILES) # 文件对象 file_obj = request.FILES.get('avatar')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')
contentType
<h3>简单的form</h3> <!-- 默认请求头是 "application/x-www-form-urlencoded" --> <form action="" method="post" enctype="application/x-www-form-urlencoded">用户名 <input type="text" name="user">密码 <input type="password" name="pwd"> </form><h3>基于form表单的文件上传</h3><!-- 请求头 multipart/form-data --> <form action="" method="post" enctype="multipart/form-data">用户名 <input type="text" name="user">头像 <input type="file" name="avatar"><input type="submit"> </form><h3>基于Ajax文件上传</h3><form action="" method="post">用户名 <input type="text"><input type="button" class="btn" value="Ajax"> </form><script>$('.btn').click(function () { // 还未实现,只是说明ajax不是用multipart/form-data上传文件的 $.ajax({url:'',type:'post',data:{ // 请求头默认也是application/x-www-form-urlencoded a:1,b:2},success:function () {console.log(data)}})}) </script>
Ajax传递json数据
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>file put</title> </head> <body> <h3>基于Ajax文件上传</h3><form action="" method="post">用户名 <input type="text"><input type="button" class="btn" value="Ajax"> </form><script src="/static/jquery-3.3.1.js"></script><script>$('.btn').click(function () {$.ajax({url:'',type:'post',contentType:'application/json',data:JSON.stringify({a:1,b:2}),success:function () {console.log(data)}})}) </script> </body> </html>
views.py
def file_put(request):if request.method == 'POST':print('body', request.body) # 请求报文中的请求体 body b'{"a":1,"b":2}'print('post', request.POST) # if contentType==urlencoded,request.POST才有数据。如果是urlencoded,那就把数据转换成字典,方便取值 post。此次传送的是json数据,所以没有值。 <QueryDict: {}>return HttpResponse('OK')return render(request, 'file_put.html')
基于Ajax的文件上传
html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>file put</title> </head> <body> <h3>基于Ajax文件上传</h3><form action="" method="post">用户名 <input type="text" id="user">头像 <input type="file" id="avatar"><input type="button" class="btn" value="Ajax"> </form><script src="/static/jquery-3.3.1.js"></script><script>$('.btn').click(function () {let formdata = new FormData();let user = $('#user').val();let avatar = $('#avatar')[0].files[0];formdata.append("user", user);formdata.append('avatar', avatar);$.ajax({url: '',type: 'post',contentType: false, // 不做任何编码processData: false, // 不到预处理data: formdata,success: function (data) {console.log(data)}})}) </script> </body> </html>
views.py
def file_put(request):if request.method == 'POST':print('post', request.POST)print('file',request.FILES)file_obj = request.FILES.get('avatar')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')
转载于:https://www.cnblogs.com/lshedward/p/10351834.html
django之Ajax相关推荐
- ajax报403错,django使用ajax post数据出现403错误如何解决
本文通过两种方法给大家介绍在django中,使用jquery ajax post数据,会出现403的错误,具体内容请看下文. 方法一: 如果用jQuery来处理ajax的话,Django直接送了一段解 ...
- django+jquery ajax post csrf 配置
2019独角兽企业重金招聘Python工程师标准>>> django+jquery ajax post csrf 配置: <body> {% csrf_token %} ...
- django 接收ajax请求
原文:http://qindongliang.iteye.com/blog/2147336 Ajax的出现让Web展现了更新的活力,基本所有的语言,都动态支持Ajax与起服务端进行通信,并在页面实现无 ...
- django+echarts+ajax异步+显示优化--基本例子
django+echarts+ajax异步+显示优化--基本例子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 2 ...
- js中ajax刷新页面,django+js+ajax实现刷新页面的方法
本文实例讲述了django+js+ajax实现刷新页面的方法.分享给大家供大家参考,具体如下: 在服务器开发的时候,为了方便将服务器对外开一个接口来操作,可以使用django制作网页,通过页面来操作服 ...
- ajax的post请求出现403错误,如何解决Django中ajax发送post请求报403错误CSRF验证失败的问题...
如何解决Django中ajax发送post请求报403错误CSRF验证失败的问题 发布时间:2021-02-05 14:23:57 来源:亿速云 阅读:92 作者:小新 这篇文章主要介绍了如何解决Dj ...
- openstack页面自定义插件使用详解(django、ajax、post)(zTree为例)
2019独角兽企业重金招聘Python工程师标准>>> 感谢朋友支持本博客,欢迎共同探讨交流,由于能力和时间有限,错误之处在所难免,欢迎指正! 如有转载,请保留源作者博客信息. Be ...
- Django 和 Ajax 简介
在Django里面,目前我们都是通过前端页面的form提交GET或者POST请求到后台,后台处理了业务函数之后,把渲染之后的字符串结果发回给前端.这样的结果是每次页面都会进行刷新. 假设一个场景我们使 ...
- Django中Ajax提交数据的CSRF问题
错误信息: Forbidden (CSRF token missing or incorrect.): 什么是CSRF: django为用户实现防止跨站请求伪造的功能,通过中间件 django.mid ...
最新文章
- 这个CV数据集生成器火了,支持13类复杂CV任务,DeepMind谷歌MIT等打造丨开源
- Rust crates.io换国内镜像源
- ExecuteScalar()如何返回整数
- Confluence 6 授权
- mysql设置数据库同步_MySQL数据库配置主从同步
- 懂得保持平衡的程序员
- HBase Shell 基本操作
- Apache服务器学习笔记
- vm客户机隔离不能选_开汽车美容店,这些位置绝对不能选,会让你门可罗雀,生意惨淡...
- input readonly 光标显示问题
- C语言的应用领域及其重要性
- 资源打包Assetbundle .
- POJ 3178 凸包+DP (巨坑)
- 油猴脚本管理器的超详细下载安装使用教程—— 个性化浏览器
- yolov3gpu配置_YOLO3-WIN10-GPU版配置详细教程
- 四川大学 计算机复试分数线,2015年四川大学考研复试分数线已公布
- 英语老师超强整理:18条小学英语语法快速记忆口诀,英语成绩次次100!
- 客户价值度和活跃度建模
- 图形学知识基础:三维变换,旋转(欧拉角旋转与万向锁,绕任意轴旋转,四元数)
- Java方法 的学习
热门文章
- 大揭秘:程序员工作也可以成为享受!
- Java 25 岁,发展现状大曝光!程序员的机会来了
- @程序员,地表最强的 CSDN 原创博主大赛来了!
- 『Python Web框架之Django』第几节: AJAX
- elasticsearch之hello(spring data整合)
- 项目三(2)——抽象类
- 中兴同美司法部和解协议获准:罚12亿美元
- Oracle NoLogging Append 方式减少批量insert的redo_size
- AngularJS控制div隐藏或显示-ng-show
- tomcat+bean例子