一、Ajax(part1)

  Ajax即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术,AJAX = 异步 JavaScript和XML(标准通用标记语言的子集),AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。传统的网页(不使用 AJAX)如果需要更新内容,必须重载整个网页页面。

1、初识

1 $.ajax({2     url: '/host',               #数据提交地址
3     type: "POST",               #提交类型
4     data: {'k1': 123, 'k2': "root"},        #提交的内容 字典格式
5     success: function(data){    #客户端会一直等待服务端返回的数值
6             #data是服务器端返回的字符串
7         var obj =JSON.parse(data);8 }9 })10
11 #建议:永远让服务器端返回一个字典
12 return HttpResponse(json.dumps(字典))

2、简单的前后端交互

 <divclass="shade hide"></div><divclass="add-modal hide"><formmethod="POST"action="/home/"><divclass="group"><inputid='host'type="text"placeholder="主机名"name="hostname" /></div><divclass="group"><inputid='ip'type="text"placeholder="IP"name="ip" /></div><divclass="group"><inputid='port'type="text"placeholder="端口"name="port" /></div><divclass="group"><selectid='sel'name="b_id">{% for op in b_list %}<optionvalue="{{ op.id }}">{{ op.caption }}</option>{% endfor %}</select></div><inputtype="submit"value="提交" /><aid="ajax_submit">要上天提交</a><inputid="cancel"type="button"value="取消" /></form></div>

#index.html

$(function(){$('#ajax_submit').click(function () {$.ajax({url:"/test_ajax/",type:"POST",data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},success:function (data) {if(data=='OK'){location.reload()   // 重新加载页面}else {alert(data);}}})})
})

#Ajax代码

deftest_ajax(request):print(request.method)h= request.POST.get('hostname')i= request.POST.get('ip')p= request.POST.get('port')b= request.POST.get('b_id')print(h,i,p,b)if h and len(h) > 5:        #主机名长度判断models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b) #创建数据return HttpResponse("OK")    #返回OK 严格大小写else:return HttpResponse("主机名太短")  #返回错误提示

#Django代码

3、对前后端交互完善(当后端有问题时,前端收不到data,页面无反应)

<divclass="add-modal hide"><formmethod="POST"action="/home/"><divclass="group"><inputid='host'type="text"placeholder="主机名"name="hostname" /></div><divclass="group"><inputid='ip'type="text"placeholder="IP"name="ip" /></div><divclass="group"><inputid='port'type="text"placeholder="端口"name="port" /></div><divclass="group"><selectid='sel'name="b_id">{% for op in b_list %}<optionvalue="{{ op.id }}">{{ op.caption }}</option>{% endfor %}</select></div><inputtype="submit"value="提交" /><aid="ajax_submit">要上天提交</a><inputid="cancel"type="button"value="取消" /><spanid="error_msg"></span></form></div>

#index.html

$(function(){$('#ajax_submit').click(function () {$.ajax({url:"/test_ajax/",type:"POST",data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},success:function (data) {console.log(data)    // data {"data": null, "status": false, "error": "\u4e3b\u673a\u540d\u592a\u77ed"}var obj = JSON.parse(data);     // 反序列化 把字符串data换成对象obj// 序列化 JSON.stringify() 把obj转换为字符串if(obj.status){location.reload()   // 重新加载页面}else {$('#error_msg').text(obj.error)}}})})
})

#Ajax代码

importjsondeftest_ajax(request):ret= {'status':True,'error':None,'data':None}  #返回一个字典try:h= request.POST.get('hostname')i= request.POST.get('ip')p= request.POST.get('port')b= request.POST.get('b_id')print(h,i,p,b)if h and len(h) > 5:        #主机名长度print("ok")models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b)else:ret['status'] =Falseret['error'] = '主机名太短'exceptException as e:ret['status'] =Falseret['error'] = '请求错误'return  HttpResponse(json.dumps(ret))       #对字典进行序列化

#Django代码

4、serialize自动获取表单数据

<formclass="add-form"method="POST"action="/home/"><divclass="group"><inputid='host'type="text"placeholder="主机名"name="hostname" /></div><divclass="group"><inputid='ip'type="text"placeholder="IP"name="ip" /></div><divclass="group"><inputid='port'type="text"placeholder="端口"name="port" /></div><divclass="group"><selectid='sel'name="b_id">{% for op in b_list %}<optionvalue="{{ op.id }}">{{ op.caption }}</option>{% endfor %}</select></div><inputtype="submit"value="提交" /><aid="ajax_submit">要上天提交</a><inputid="cancel"type="button"value="取消" /><spanid="error_msg"></span></form>

#index.html

$.ajax({url:"/test_ajax/",type:"POST",        data:$('.add-form').serialize(),  //获取表单数据提交 必须是form表单success:function (data) {})

#Ajax代码

5、Ajax代码补充(traditional,dataType)

$(function(){$('#add_submit_ajax').click(function(){$.ajax({url: '/ajax_add_app',data: {'user': 123,'host_list': [1,2,3,4]},// data: $('#add_form').serialize(),type: "POST",dataType: 'JSON',       // 内部对传过来的数据直接执行JSON.parse 拿到的数据直接为对象而非字符串traditional: true,      // 添加此项 当字典里包含列表时候,后端可以getlist到里面的数据success: function(obj){console.log(obj);},error: function () {     // 未知错误时执行,指前端收不到后台发送的obj时,执行}})});
})

#Ajax代码

defajax_add_app(request):ret= {'status':True, 'error':None, 'data': None}app_name= request.POST.get('app_name')host_list= request.POST.getlist('host_list')obj= models.Application.objects.create(name=app_name)obj.r.add(*host_list)return HttpResponse(json.dumps(ret))

#Django代码

6、页面跳转和刷新

$.ajax({url: '/index/',data: {'k': 'v', 'list': [1,2,3,4], 'k3': JSON.stringfy({'k1': 'v'}))}, $(form对象).serilize()type: 'POST',dataType: 'JSON':traditional: true,success:function(d){location.reload()              # 刷新location.href = "某个地址"     # 跳转}
})

View Code

二、 Ajax(part2)

原生Ajax、JQuery、伪Ajax三种方式使用优先级:

  如果发送的是【普通数据】: jQuery > XMLHttpRequest > iframe
  如果发送的是【文件】 :      iframe > jQuery(FormData) > XMLHttpRequest(FormData)

①原生Ajax操作
Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)
1、XmlHttpRequest对象介绍

a. void open(String method,String url,Boolen async)用于创建请求参数:method: 请求方式(字符串类型),如:POST、GET、DELETE...url:    要请求的地址(字符串类型)async:  是否异步(布尔类型)b. void send(String body)用于发送请求参数:body: 要发送的数据(字符串类型)c. void setRequestHeader(String header,String value)用于设置请求头参数:header: 请求头的key(字符串类型)vlaue:  请求头的value(字符串类型)d. String getAllResponseHeaders()获取所有响应头返回值:响应头数据(字符串类型)e. String getResponseHeader(String header)获取响应头中指定header的值参数:header: 响应头的key(字符串类型)返回值:响应头中指定的header对应的值f. void abort()终止请求

#主要方法

a. Number readyState状态值(整数)详细:0-未初始化,尚未调用open()方法;1-启动,调用了open()方法,未调用send()方法;2-发送,已经调用了send()方法,未接收到响应;3-接收,已经接收到部分响应数据;4-完成,已经接收到全部响应数据;b. Function onreadystatechange当readyState的值改变时自动触发执行其对应的函数(回调函数)c. String responseText服务器返回的数据(字符串类型)d. XmlDocument responseXML服务器返回的数据(Xml对象)e. Number states状态码(整数),如:200、404...f. String statesText状态文本(字符串),如:OK、NotFound...

#主要属性

2、用原生Ajax做个请求

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title>
</head>
<body><inputtype="text"/><inputtype="button"value="Ajax1"onclick="Ajax1();" /><script>functionAjax1(){varxhr= newXMLHttpRequest();xhr.open('POST','/ajax_json/',true);xhr.onreadystatechange= function(){if(xhr.readyState== 4){//接收完毕varobj=JSON.parse(xhr.responseText);console.log(obj);}};xhr.setRequestHeader('k1','v1');//post请求必须加下面这句请求头 不然后台数据拿不到
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset-UTF-8');xhr.send("name=root;pwd=123");}</script>
</body>
</html>

#HTML文件

defajax(request):return render(request,'ajax.html')defajax_json(request):print(request.POST)ret= {'code':True,'data':None}importjsonreturn HttpResponse(json.dumps(ret))

#views文件

3、跨浏览器支持
XmlHttpRequest(IE7+, Firefox, Chrome, Opera, etc.)
ActiveXObject("Microsoft.XMLHTTP")(IE6, IE5)

<!DOCTYPE html>
<html>
<headlang="en"><metacharset="UTF-8"><title></title>
</head>
<body><h1>XMLHttpRequest - Ajax请求</h1><inputtype="button"onclick="XmlGetRequest();"value="Get发送请求" /><inputtype="button"onclick="XmlPostRequest();"value="Post发送请求" /><scriptsrc="/statics/jquery-1.12.4.js"></script><scripttype="text/javascript">functionGetXHR(){varxhr= null;if(XMLHttpRequest){xhr= newXMLHttpRequest();}else{xhr= newActiveXObject("Microsoft.XMLHTTP");}returnxhr;}functionXhrPostRequest(){varxhr=GetXHR();//定义回调函数
xhr.onreadystatechange= function(){if(xhr.readyState== 4){//已经接收到全部响应数据,执行以下操作vardata=xhr.responseText;console.log(data);}};//指定连接方式和地址----文件方式
xhr.open('POST',"/test/",true);//设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset-UTF-8');//发送请求
xhr.send('n1=1;n2=2;');}functionXhrGetRequest(){varxhr=GetXHR();//定义回调函数
xhr.onreadystatechange= function(){if(xhr.readyState== 4){//已经接收到全部响应数据,执行以下操作vardata=xhr.responseText;console.log(data);}};//指定连接方式和地址----文件方式
xhr.open('get',"/test/",true);//发送请求
xhr.send();}</script></body>
</html>

#基于原生AJAX - Demo

②“伪”AJAX
由于HTML标签的iframe标签具有局部加载内容的特性,所以可以使用其来伪造Ajax请求,进行偷偷的发送请求

defajax(request):return render(request,'ajax.html')defajax_json(request):print(request.POST)ret= {'code':True,'data':None}importjsonreturn HttpResponse(json.dumps(ret))

#处理文件

1.Form表单提交到iframe中,页面不刷新

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title>
</head>
<body><inputtype="text"/><inputtype="button"value="Ajax1"onclick="Ajax1();" /><formaction="/ajax_json/"method="POST"target="ifm1"> <!--target跟iframe进行关联--><iframeid="ifm1"name="ifm1" ></iframe><inputtype="text"name="username" /><inputtype="text"name="email" /><inputtype="submit"value="Form提交"/></form>
</body>
</html>

View Code

2.Ajax提交到iframe中,页面不刷新

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title>
</head>
<body><inputtype="text"/><inputtype="button"value="Ajax1"onclick="Ajax1();" /><inputtype='text'id="url" /><inputtype="button"value="发送Iframe请求"onclick="iframeRequest();" /><iframeid="ifm"src="http://www.baidu.com"></iframe><scriptsrc="/static/jquery-1.12.4.js"></script><script>functioniframeRequest(){varurl=$('#url').val();$('#ifm').attr('src',url);}</script>
</body>
</html>

View Code

3.Form表单提交到iframe中,并拿到iframe中的数据

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title>
</head>
<body><inputtype="text"/><inputtype="button"value="Ajax1"onclick="Ajax1();" /><formaction="/ajax_json/"method="POST"target="ifm1"><iframeid="ifm1"name="ifm1" ></iframe><inputtype="text"name="username" /><inputtype="text"name="email" /><inputtype="submit"onclick="sumitForm();"value="Form提交"/></form><scripttype="text/javascript"src="/static/jquery-1.12.4.js"></script><script>functionsumitForm(){$('#ifm1').load(function(){vartext=$('#ifm1').contents().find('body').text();varobj=JSON.parse(text);console.log(obj)})}</script>
</body>
</html>

View Code

三、XmlHttpRequest、JQuery、Iframe进行文件上传 

defupload(request):return render(request,'upload.html')defupload_file(request):username= request.POST.get(('username'))fafafa= request.FILES.get('fafafa')        #获取文件
with open(fafafa.name,'wb') as f:for item infafafa.chunks():f.write(item)print(username,fafafa)ret= {'code': True, 'data': request.POST.get('username')}importjsonreturn HttpResponse(json.dumps(ret))

#处理文件

① 原生Ajax(XmlHttpRequest)上传文件+定制好看的上传按钮

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title><style>.upload{display:inline-block;padding:10px;background-color:brown;position:absolute;top:0;bottom:0;right:0;left:0;z-index:90;}.file{width:100px;height:50px;opacity:0;position:absolute;top:0;bottom:0;right:0;left:0;z-index:100;}</style>
</head>
<body><divstyle="position: relative;width: 100px;height: 50px;"><inputclass="file"type="file"id="fafafa"name="afafaf" /><aclass="upload">上传</a></div><inputtype="button"value="提交XHR"onclick="xhrSubmit();" /><script>functionxhrSubmit(){//$('#fafafa')[0]varfile_obj=document.getElementById('fafafa').files[0];//获取文件对象varfd= newFormData();       fd.append('username','root');fd.append('fafafa',file_obj);varxhr= newXMLHttpRequest();xhr.open('POST','/upload_file/',true);xhr.onreadystatechange= function(){if(xhr.readyState== 4){//接收完毕varobj=JSON.parse(xhr.responseText);console.log(obj);}};xhr.send(fd);}</script>
</body>
</html>

View Code

② JQuery进行文件的上传

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title><style>.upload{display:inline-block;padding:10px;background-color:brown;position:absolute;top:0;bottom:0;right:0;left:0;z-index:90;}.file{width:100px;height:50px;opacity:0;position:absolute;top:0;bottom:0;right:0;left:0;z-index:100;}</style>
</head>
<body><divstyle="position: relative;width: 100px;height: 50px;"><inputclass="file"type="file"id="fafafa"name="afafaf" /><aclass="upload">上传</a></div>{#<inputtype="button"value="提交XHR"onclick="xhrSubmit();" />#}<inputtype="button"value="提交jQuery"onclick="jqSubmit();" /><divid="preview"></div><scriptsrc="/static/jquery-1.12.4.js"></script><script>functionjqSubmit(){//$('#fafafa')[0]varfile_obj=document.getElementById('fafafa').files[0];varfd= newFormData();fd.append('username','root');fd.append('fafafa',file_obj);$.ajax({url:'/upload_file/',type:'POST',data: fd,processData:false,//tell jQuery not to process the data
contentType:false,//tell jQuery not to set contentType
success:function(arg,a1,a2){console.log(arg);console.log(a1);console.log(a2);//Object {readyState: 4, responseText: "{"data": "root", "code": true}", status: 200, statusText: "OK"}
}})}</script>
</body>
</html>

View Code

上面两种方式都用到FormData(),但是如果是IE浏览器的话是不支持FormData(),所以就得用到下面这种方式。
③ Iframe进行文件的上传

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title>
</head>
<body><formid="form1"action="/upload_file/"method="POST"enctype="multipart/form-data"target="ifm1"><iframeid="ifm1"name="ifm1"style="display: none;"></iframe><inputtype="file"name="fafafa"  /><inputtype="submit"onclick="iframeSubmit();"value="Form提交"/></form><scriptsrc="/static/jquery-1.12.4.js"></script><script>functioniframeSubmit(){$('#ifm1').load(function(){vartext=$('#ifm1').contents().find('body').text();varobj=JSON.parse(text);console.log(obj)})}</script>
</body>
</html>

View Code

四、上传文件时图片预览 

① 点击上传文件提交

defupload(request):return render(request,'upload.html')defupload_file(request):username= request.POST.get(('username'))fafafa= request.FILES.get('fafafa')        #获取文件importosimg_path= os.path.join('static/imgs/',fafafa.name)     #static下创建imgs目录with open(img_path,'wb') as f:for item infafafa.chunks():f.write(item)print(username,fafafa)ret= {'code': True, 'data': img_path}importjsonreturn HttpResponse(json.dumps(ret))

#处理文件

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title>
</head>
<body><formid="form1"action="/upload_file/"method="POST"enctype="multipart/form-data"target="ifm1"><iframeid="ifm1"name="ifm1"style="display: none;"></iframe><inputtype="file"name="fafafa"  /><inputtype="submit"onclick="iframeSubmit();"value="Form提交"/></form><divid="preview"></div><scriptsrc="/static/jquery-1.12.4.js"></script><script>functioniframeSubmit(){$('#ifm1').load(function(){vartext=$('#ifm1').contents().find('body').text();varobj=JSON.parse(text);console.log(obj)$('#preview').empty();varimgTag=document.createElement('img');imgTag.src= "/" +obj.data;$('#preview').append(imgTag);})}</script>
</body>
</html>

#HTML文件

② 选择文件后,直接上传

<!DOCTYPE html>
<htmllang="en">
<head><metacharset="UTF-8"><title></title>
</head>
<body><formid="form1"action="/upload_file/"method="POST"enctype="multipart/form-data"target="ifm1"><iframeid="ifm1"name="ifm1"style="display: none;"></iframe><inputtype="file"name="fafafa"onchange="changeUpalod();" />//onchange 选中文件时触发
{#<inputtype="submit"onclick="iframeSubmit();"value="Form提交"/>#}</form><divid="preview"></div><scriptsrc="/static/jquery-1.12.4.js"></script><script>functionchangeUpalod(){$('#ifm1').load(function(){                //load  绑定load事件,有数据时执行vartext=$('#ifm1').contents().find('body').text();varobj=JSON.parse(text);$('#preview').empty();varimgTag=document.createElement('img');imgTag.src= "/" +obj.data;$('#preview').append(imgTag);});$('#form1').submit();}</script>
</body>
</html>

#HTML文件

转载于:https://www.cnblogs.com/liwei1153300111/p/8391270.html

Python学习笔记整理总结【Django】Ajax相关推荐

  1. python 学习笔记十九 django深入学习四 cookie,session

    缓存 一个动态网站的基本权衡点就是,它是动态的. 每次用户请求一个页面,Web服务器将进行所有涵盖数据库查询到模版渲染到业务逻辑的请求,用来创建浏览者需要的页面.当程序访问量大时,耗时必然会更加明显, ...

  2. Python学习笔记整理(十六)类的设计

    如何使用类来对有用的对象进行建模? 一.Python和OOP Python和OOP实现可以概括为三个概念. 继承     继承是基于Python中属性查找(在X.name表达式中) 多态     在X ...

  3. Python学习笔记整理(十五)类的编写细节

    类代码编写细节 一.class语句 一般形式 class    <name>(superclass,...):     data=value     def mothod(self,... ...

  4. Python学习笔记整理(三)Python中的动态类型简介

    Python中只有一个赋值模型 一.缺少类型声明语句的情况 在Python中,类型是在运行过程中自动决定的,而不是通过代码声明.这意味着没有必要事声明变量.只要记住,这个概念实质上对变量,对象和它们之 ...

  5. python学习笔记整理tcy1: with上下文管理

    上下文管理器类型 2018/7/8 https://docs.python.org/3.7/library/ 参考书:Python参考手册+第4版_修订版 ---------------------- ...

  6. python eval 入门_Python学习笔记整理3之输入输出、python eval函数

    Python学习笔记整理3之输入输出.python eval函数 来源:中文源码网    浏览: 次    日期:2018年9月2日 Python学习笔记整理3之输入输出.python eval函数 ...

  7. Python学习笔记--10.Django框架快速入门之后台管理admin(书籍管理系统)

    Python学习笔记--10.Django框架快速入门之后台管理 一.Django框架介绍 二.创建第一个Django项目 三.应用的创建和使用 四.项目的数据库模型 ORM对象关系映射 sqlite ...

  8. python学习笔记目录

    人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...

  9. python学习笔记_week14

    python学习笔记_week14 Web框架本质 众所周知,对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端. s1 1 import sock ...

  10. python学习笔记_week22

    python学习笔记_week22 note 知识点概要- Session- CSRF- Model操作- Form验证(ModelForm)- 中间件- 缓存- 信号 内容详细: 1. Sessio ...

最新文章

  1. scrapy item引用时报错
  2. Spring Cloud Feign - 内部实现细节
  3. python循环中的else_python 循环中else的简单示例
  4. matlab火焰测温源程序,一种火焰测温方法与流程
  5. qt中 accept()和ignore()函数
  6. GridView控件 72变(一)
  7. python网络爬虫的特点_Python网络爬虫(一)- 入门基础
  8. leetcodepython_LeetCode 答案(python)1-17
  9. 计算机学术论文3000字,计算机学术论文3000字_计算机学术毕业论文范文模板.doc...
  10. tts文字转语音_最佳文字转语音(TTS)软件程序和在线工具
  11. 日语N2听力常用词汇
  12. 2014年FME校园培训考核通过名单
  13. WebStorm的下载与安装
  14. Matlab 矩阵元素选取方法
  15. JavaScript实现放大镜预览效果
  16. 边城科技“区块链+溯源”平台助力坪朗豆腐品牌升级
  17. 初中物理公式总结大全(pdf可下载)
  18. Hyperledger系列(十二)MSP详细介绍
  19. 格力何时实行周末双休?董明珠回应:社会需要时,要放下自我
  20. 从0到1项目搭建-框架搭建(附源码)

热门文章

  1. activexobject对象不能创建_Java面向对象总结
  2. solidity import @是什么意思
  3. java并发编程(13)-- 线程 死锁和定位
  4. 将linux系统分区变成逻辑卷,linux运维基础知识-系统分区及LVM逻辑卷的创建
  5. Mybatis框架中${}和#{}的区别
  6. 计算机设备硬件设备,计算机硬件设备有哪些
  7. vscode还用装git_在windows下搭建编程环境git+vscode安装配置教程
  8. guava 工具类及代码
  9. 算数基本定理 + 例题
  10. MongoDB 固定集合详解