1.ajax
概述:
AJAX = 異步 JavaScript 和 XML。
AJAX 是一種用於創建快速動態網頁的技術。
通過在后台與服務器進行少量數據交換,AJAX 可以使網頁實現異步更新。這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新,而傳統的網頁(不使用 AJAX)如果需要更新內容,必需重載整個網頁面。
1.1 原生Ajax
原生Ajax主要就是使用 【XmlHttpRequest】對象來完成請求的操作,該對象在主流瀏覽器中均存在(除早起的IE),Ajax首次出現IE5.5中存在(ActiveX控件)。
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() 終止請求
XmlHttpRequest對象的主要屬性:
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...
基於原生AJAX案例:

from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^ajax/', views.ajax), url(r'^json/', views.json), ]

def ajax(request): return render(request,'ajax.html') def json(requset): ret = {'status':True,'data':None)} import json return HttpResponse(json.dumps(ret))

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text"/> <input type="button" value="Ajax1" onclick="Ajax1();"/> <script src="/static/jquery-1.12.4.js/"></script> <script> //跨瀏覽器支持 function getXHR(){ var xhr = null; if(XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } return xhr; } function Ajax1() { var xhr = new getXHR(); xhr.open('POST','/json/',true); xhr.onreadystatechange = function () { if(xhr.readyState == 4){ //接收完畢,執行以下操作 //console.log(xhr.responseText); var obj = JSON.parse(xhr.responseText); console.log(obj); } }; // 設置請求頭,后端輸入print(requset.POST),可獲取send數據 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); //只能是字符串格式 xhr.send("name=root;pwd=123") } </script> </body> </html>
1.2 ajax jquery
jQuery其實就是一個JavaScript的類庫(JS框架),其將復雜的功能做了上層封裝,使得開發者可以在其基礎上寫更少的代碼實現更多的功能。
- jQuery 不是生產者,而是大自然搬運工。
- jQuery Ajax本質 XMLHttpRequest 或 ActiveXObject
jQuery Ajax 方法列表:
jQuery.get(...) 所有參數: 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信息返回相應類型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string 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; } }, });
基於jQueryAjax-demo
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <p> <input type="button" onclick="XmlSendRequest();" value='Ajax請求' /> </p> <script type="text/javascript" src="jquery-1.12.4.js"></script> <script> function JqSendRequest(){ $.ajax({ url: "http://c2.com:8000/test/", // 數據提交地址 type: 'GET', //提交類型 dataType: 'text', //提交的內容 字典格式 success: function(data, statusText, xmlHttpRequest){ console.log(data); // data是服務器端返回的字符串 var obj = JSON.parse(data); // 反序列化 把字符串data換成對象obj // 序列化 JSON.stringify() 把obj轉換為字符串 if(obj.status){ location.reload() // 重新加載頁面 }else { $('#error_msg').text(obj.error) } } }) } </script> </body> </html> # 建議:永遠讓服務器端返回一個字典 # return HttpResponse(json.dumps(字典))
1.3 “偽”AJAX
由於HTML標簽的iframe標簽具有局部加載內容的特性,所以可以使用其來偽造Ajax請求。
① Form表單提交到iframe中,頁面不刷新
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="text"/> <input type="button" value="Ajax1" onclick="Ajax1();" /> <form action="/ajax_json/" method="POST" target="ifm1"> <!-- target跟iframe進行關聯 --> <iframe id="ifm1" name="ifm1" ></iframe> <input type="text" name="username" /> <input type="text" name="email" /> <input type="submit" value="Form提交"/> </form> </body> </html>②.Ajax提交到iframe中,頁面不刷新
② Ajax提交到iframe中,頁面不刷新
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="text"/> <input type="button" value="Ajax1" onclick="Ajax1();" /> <input type='text' id="url" /> <input type="button" value="發送Iframe請求" onclick="iframeRequest();" /> <iframe id="ifm" src="http://www.baidu.com"></iframe> <script src="/static/jquery-1.12.4.js"></script> <script> function iframeRequest(){ var url = $('#url').val(); $('#ifm').attr('src',url); } </script> </body> </html>③.Form表單提交到iframe中,並拿到iframe中的數據
③ Form表單提交到iframe中,並拿到iframe中的數據
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="text"/> <input type="button" value="Ajax1" onclick="Ajax1();" /> <form action="/ajax_json/" method="POST" target="ifm1"> <iframe id="ifm1" name="ifm1" ></iframe> <input type="text" name="username" /> <input type="text" name="email" /> <input type="submit" onclick="submitForm();" value="Form提交"/> </form> <script type="text/javascript" src="/static/jquery-1.12.4.js"></script> <script> function submitForm(){ $('#ifm1').load(function(){ var text = $('#ifm1').contents().find('body').text(); var obj = JSON.parse(text); console.log(obj) }) } </script> </body> </html>
2.上傳文件
2.1 Form表單上傳

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload.html" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="user"/> <input type="file" name="img"/> <input type="submit" value="提交"> </form> </body> </html>

from django.shortcuts import render from django.shortcuts import HttpResponse # Create your views here. def upload(request): if request.method == "GET": return render(request,'upload.html') else: user = request.POST.get('user') img = request.FILES.get('img') #img是個對象(文件大小,文件名稱,文件內容...) print(img.name) print(img.size) n = open(img.name,'wb') for i in img.chunks(): n.write(i) n.close() return HttpResponse('...!')
偽裝上傳按鈕樣式

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload.html" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="user"/> <div style="position: relative"> <a>上傳圖片</a> <input type="file" name="img" style="opacity: 0.2;position:absolute;top: 0;left: 0" /> </div> <input type="submit" value="提交"> </form> </body> </html>
2.2 AJAX上傳
基於原生Aja(XmlHttpRequest)上傳文件

from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^upload/$', views.upload), url(r'^upload_file/$', views.upload_file), ]

def upload(request): return render(request,'upload.html') def upload_file(request): username = request.POST.get('username') send = request.FILES.get('send') print(username,send) with open(send.name,'wb') as f: for item in send.chunks(): f.write(item) ret = {'status': True, 'data': request.POST.get('username')} import json return HttpResponse(json.dumps(ret))

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .upload{ display: inline-block;padding: 5px 10px; background-color: dodgerblue; position: absolute; top: 0px; left: 0px; right: 0px; bottom:0px; z-index: 90; } .file{ width: 100px;height: 50px;opacity: 0; position: absolute; top: 0px; left: 0px; right: 0px; bottom:0px; z-index: 100; } </style> </head> <body> <div style="position: relative;width: 100px;height: 50px"> <input class="file" type="file" id="send" name="afafaf"/> <a class="upload">上傳</a> </div> <input type="button" value="提交xmlhttprequest" onclick="xhrSubmit();"/> <script> function xhrSubmit() { //$('#send')[0] var file_obj = document.getElementById('send').files[0]; var fd = new FormData(); fd.append('username','root'); fd.append('send',file_obj); var xhr = new XMLHttpRequest(); xhr.open('POST','/upload_file/',true); xhr.send(fd); xhr.onreadystatechange = function () { if(xhr.readyState == 4){ //接收完畢,執行以下操作 //console.log(xhr.responseText); var obj = JSON.parse(xhr.responseText); console.log(obj); } }; } </script> </body> </html>
基於Ajax JQuery進行文件的上傳文件

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .upload{ display: inline-block;padding: 5px 10px; background-color: dodgerblue; position: absolute; top: 0px; left: 0px; right: 0px; bottom:0px; z-index: 90; } .file{ width: 100px;height: 50px;opacity: 0; position: absolute; top: 0px; left: 0px; right: 0px; bottom:0px; z-index: 100; } </style> </head> <body> <div style="position: relative;width: 100px;height: 50px"> <input class="file" type="file" id="send" name="afafaf"/> <a class="upload">上傳</a> </div> <input type="button" value="提交jquery" onclick="jqSubmit();"> <script src="/static/jquery-1.12.4.js/"></script> <script> function jqSubmit(){ //$('#send')[0] var file_obj = document.getElementById('send').files[0]; var fd = new FormData(); fd.append('username', 'root'); fd.append('send', 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); } }) } </script> </body> </html>
Iframe進行文件的上傳

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/upload_file/" enctype="multipart/form-data" target="ifm1"> <iframe id="iframe" name="ifm1" style="display: none"></iframe> <input type="file" name="send"/> <input type="submit" onclick="iframesubmit()" value="Form表單提交"/> </form> <script src="/static/jquery-1.12.4.js/"></script> <script> function iframesubmit() { $("#iframe").load(function () { var text = $('#iframe').contents().find('body').text(); var obj = JSON.parse(text); console.log(obj); }) } </script> </body> </html>
3.圖片預覽
3.1上傳圖片后預覽

def upload(request): return render(request,'upload.html') def upload_file(request): username = request.POST.get('username') send = request.FILES.get('send') print(username, send) import os img_path = os.path.join('static/imgs/',send.name) with open(img_path, 'wb') as f: for item in send.chunks(): f.write(item) ret = {'status': True, 'data': img_path} import json return HttpResponse(json.dumps(ret))

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1"> <iframe id="ifm1" name="ifm1" style="display: none;"></iframe> <input type="file" name="fafafa" /> <input type="submit" onclick="iframeSubmit();" value="Form提交"/> </form> <div id="preview"></div> <script src="/static/jquery-1.12.4.js"></script> <script> function iframeSubmit(){ $('#ifm1').load(function(){ var text = $('#ifm1').contents().find('body').text(); var obj = JSON.parse(text); console.log(obj) //上傳后增加預覽模式 $('#preview').empty(); //清空原有相同文件 var imgTag = document.createElement('img'); //創建img標簽 imgTag.src = "/" + obj.data; //路徑 $('#preview').append(imgTag); }) } </script> </body> </html> #HTML文件
3.2選擇圖片后預覽

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form id="form1" method="post" action="/upload_file/" enctype="multipart/form-data" target="ifm1"> <iframe id="iframe" name="ifm1" style="display: none"></iframe> <input type="file" name="send" onchange="changeupload();"/> {# <input type="submit" onclick="iframesubmit()" value="Form表單提交"/>#} </form> <div id="preview"></div> <script src="/static/jquery-1.12.4.js"></script> <script> function changeupload() { $("#iframe").load(function () { var text = $('#iframe').contents().find('body').text(); var obj = JSON.parse(text); console.log(obj) //上傳后增加預覽模式 $('#preview').empty();//清空原有相同文件 var imgTag = document.createElement('img');//創建img標簽 imgTag.src = "/" + obj.data;//路徑 $('#preview').append(imgTag); }) $('#form1').submit(); } </script> </body> </html> #HTML文件