AJAX,Asynchronous JavaScript and XML (异步的JavaScript和XML),一种建立交互式网页应用的网页开发技术方案。javascript
经过在后台与服务器进行少许数据交换,Ajax 能够使网页实现异步更新。这意味着能够在不从新加载整个网页的状况下,对网页的某部分进行更新。传统的网页(不使用 Ajax)若是须要更新内容,必须重载整个网页页面。html
Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操做,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。java
XmlHttpRequest对象的属性和方法jquery
function AjaxSubmit2() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4){ //接收完毕服务器返回的数据 console.log(xhr.responseText) } }; xhr.open('GET', '/ajax?p=123'); xhr.send(null) }
function AjaxSubmit3() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if(xhr.readyState === 4){ //接收完毕服务器的数据 console.log(xhr.responseText) } }; xhr.open('POST', '/ajax'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); xhr.send('p=123; a=456') }
jQuery其实就是一个JavaScript的类库,其将复杂的功能作了上层封装,使得开发者能够在其基础上写更少的代码实现更多的功能。ajax
全部参数: url: 待载入页面的URL地址 data: 待发送 Key/value 参数。 success: 载入成功时回调函数。 dataType: 返回内容格式,xml, json, script, text, html jQuery.post(...) 全部参数: url: 待载入页面的URL地址 data: 待发送 Key/value 参数 success: 载入成功时回调函数 dataType: 返回内容格式,xml, json, script, text, html jQuery.getJSON(...) 全部参数: url: 待载入页面的URL地址 data: 待发送 Key/value 参数。 success: 载入成功时回调函数。 jQuery.getScript(...) 全部参数: url: 待载入页面的URL地址 data: 待发送 Key/value 参数。 success: 载入成功时回调函数。 jQuery.ajax(...) 部分参数: url:请求地址 type:请求方式,GET、POST(1.9.0以后用method) headers:请求头 data:要发送的数据 contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8") async:是否异步 timeout:设置请求超时时间(毫秒) beforeSend:发送请求前执行的函数(全局) complete:完成以后执行的回调函数(全局) success:成功以后执行的回调函数(全局) error:失败以后执行的回调函数(全局) accepts:经过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型 dataType:将服务器端返回的数据转换成指定类型 "xml": 将服务器端返回的内容转换成xml格式 "text": 将服务器端返回的内容转换成普通文本格式 "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,若是包含JavaScript标签,则会尝试去执行。 "script": 尝试将返回值看成JavaScript去执行,而后再将服务器端返回的内容转换成普通文本格式 "json": 将服务器端返回的内容转换成相应的JavaScript对象 "jsonp": JSONP 格式 使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数 若是不指定,jQuery 将自动根据HTTP包MIME信息返回相应类型
converters: 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数 $.ajax({ accepts: { mycustomtype: 'application/x-some-custom-type' }, // Expect a `mycustomtype` back from server dataType: 'mycustomtype' // Instructions for how to deserialize a `mycustomtype` converters: { 'text mycustomtype': function(result) { // Do Stuff return newresult; } }, });
使用jQuery Ajax上传文件json
<input id="file" type="file"> <button onclick="new AjaxSubmit4()">上传</button> function AjaxSubmit4() { var data = new FormData(); data.append('k1', document.getElementById('file').files[0]); $.ajax({ url: '/ajax', type: 'POST', data: data, success: function (arg) { console.log(arg) }, processData: false, contentType: false }) }
因为HTML标签的iframe标签具备局部加载内容的特性,因此能够使用其来伪造Ajax请求。跨域
<iframe id="ifr" name="ifr"></iframe> <form action="/ajax" id="form" method="post" target="ifr"> <input type="text"> <a onclick="submit()">提交</a> </form> function submit(){ document.getElementById('ifr').onload = reloadIframe; document.getElementById('form').submit() } function reloadIframe(){ //var content = $(this).contents().find('body').html() var content = this.contentWindow.document.body.innerHTML; var obj = JSON.parse(content); if(obj.status){ alert(obj.data) } } # view函数 def ajax(request): import json res = {'status': True, 'data': '...'} print(request.GET) print(request.POST) print(request.FILES) return HttpResponse(json.dumps(res))
使用iframe上传文件浏览器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <iframe name="iframe" id="iframe"></iframe> <form action="/upload" id="fm" method="post" enctype="multipart/form-data"> <input type="file" name="img" onchange="upload()"> </form> </body> <script src="/static/js/jquery-3.4.1.js"></script> <script> function upload(){ document.getElementById('iframe').onload = loadIframe; document.getElementById('fm').submit() } function loadIframe() { var content = this.contentWindow.document.body.innerHTML; var obj = JSON.parse(content); if(obj.status){ alert(obj.data) } } </script> </html>
def upload(request): if request.method == 'GET': return render(request, 'upload.html') else: res = {'status': True, 'data': '...'} img = request.FILES.get('img') img_root = os.path.join('static', img.name) f = open(img_root, 'wb') for line in img.chunks(): f.write(line) f.close() return HttpResponse(json.dumps(res))
因为浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取或设置另外一个源加载的文档的属性。服务器
特别的:因为同源策略是浏览器的限制,因此请求的发送和响应是能够进行,只不过浏览器不接受罢了。app
浏览器同源策略并非对全部的请求均制约:
跨域,跨域名访问,如:http://www.c1.com 域名向 http://www.c2.com域名发送请求。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <p> <input type="button" onclick="Jsonp1();" value='提交'/> </p> <p> <input type="button" onclick="Jsonp2();" value='提交'/> </p> <script type="text/javascript" src="jquery-1.12.4.js"></script> <script> function Jsonp1(){ var tag = document.createElement('script'); tag.src = "http://c2.com:8000/test/"; document.head.appendChild(tag); document.head.removeChild(tag); } function Jsonp2(){ $.ajax({ url: "http://c2.com:8000/test/", type: 'GET', dataType: 'JSONP', jsonp: 'callback', jsonpCallback: 'list', }) } function list(arg){ console.log(arg) } </script> </body> </html>
随着技术的发展,如今的浏览器能够支持主动设置从而容许跨域请求,即:跨域资源共享(CORS,Cross-Origin Resource Sharing),其本质是设置响应头,使得浏览器容许跨域请求。