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),其本質是設置響應頭,使得瀏覽器容許跨域請求。