ajax的優缺點javascript
AJAX使用Javascript技術向服務器發送異步請求css
AJAX無須刷新整個頁面html
由於服務器響應內容再也不是整個頁面,而是頁面中的局部,因此AJAX性能高前端
小練習:計算兩個數的和java
方式一:這裏沒有指定contentType:默認是urlencode的方式發的jquery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width"> <title>Title</title> <script src="/static/jquery-3.2.1.min.js"></script> <script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script> </head> <body> <h1>計算兩個數的和,測試ajax</h1> <input type="text" class="num1">+<input type="text" class="num2">=<input type="text" class="ret"> <button class="send_ajax">sendajax</button> <script> $(".send_ajax").click(function () { $.ajax({ url:"/sendAjax/", type:"post", headers:{"X-CSRFToken":$.cookie('csrftoken')}, data:{ num1:$(".num1").val(), num2:$(".num2").val(), }, success:function (data) { alert(data); $(".ret").val(data) } }) }) </script> </body> </html>
def index(request): return render(request,"index.html") def sendAjax(request): print(request.POST) print(request.GET) print(request.body) num1 = request.POST.get("num1") num2 = request.POST.get("num2") ret = float(num1)+float(num2) return HttpResponse(ret)
方式二:指定conentType爲json數據發送:ajax
<script> $(".send_ajax").click(function () { $.ajax({ url:"/sendAjax/", type:"post", headers:{"X-CSRFToken":$.cookie('csrftoken')}, //若是是json發送的時候要用headers方式解決forbidden的問題 data:JSON.stringify({ num1:$(".num1").val(), num2:$(".num2").val() }), contentType:"application/json", //客戶端告訴瀏覽器是以json的格式發的數據,因此的吧發送的數據轉成json字符串的形式發送 success:function (data) { alert(data); $(".ret").val(data) } }) }) </script>
def sendAjax(request): import json print(request.POST) #<QueryDict: {}> print(request.GET) #<QueryDict: {}> print(request.body) #b'{"num1":"2","num2":"2"}' 注意這時的數據再也不POST和GET裏,而在body中 print(type(request.body.decode("utf8"))) # <class 'str'> # 因此取值的時候得去body中取值,首先得反序列化一下 data = request.body.decode("utf8") data = json.loads(data) num1= data.get("num1") num2 =data.get("num2") ret = float(num1)+float(num2) return HttpResponse(ret)
其實AJAX就是在Javascript中多添加了一個對象:XMLHttpRequest對象。全部的異步交互都是使用XMLHttpServlet對象完成的。也就是說,咱們只須要學習一個Javascript的新對象便可。django
var xmlHttp = new XMLHttpRequest();(大多數瀏覽器都支持DOM2規範)
注意,各個瀏覽器對XMLHttpRequest的支持也是不一樣的!爲了處理瀏覽器兼容問題,給出下面方法來建立XMLHttpRequest對象:json
function createXMLHttpRequest() { var xmlHttp; // 適用於大多數瀏覽器,以及IE7和IE更高版本 try{ xmlHttp = new XMLHttpRequest(); } catch (e) { // 適用於IE6 try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { // 適用於IE5.5,以及IE更早版本 try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return xmlHttp; }
當獲得XMLHttpRequest對象後,就能夠調用該對象的open()方法打開與服務器的鏈接了。open()方法的參數以下:跨域
open(method, url, async):
method:請求方式,一般爲GET或POST;
url:請求的服務器地址,例如:/ajaxdemo1/AServlet,若爲GET請求,還能夠在URL後追加參數;
async:這個參數能夠不給,默認值爲true,表示異步請求;
當使用open打開鏈接後,就能夠調用XMLHttpRequest對象的send()方法發送請求了。send()方法的參數爲POST請求參數,即對應HTTP協議的請求體內容,如果GET請求,須要在URL後鏈接參數。
注意:若沒有參數,須要給出null爲參數!若不給出null爲參數,可能會致使FireFox瀏覽器不能正常發送請求!
xmlHttp.send(null);
當請求發送出去後,服務器端就開始執行了,但服務器端的響應尚未接收到。接下來咱們來接收服務器的響應。
XMLHttpRequest對象有一個onreadystatechange事件,它會在XMLHttpRequest對象的狀態發生變化時被調用。下面介紹一下XMLHttpRequest對象的5種狀態:
0:初始化未完成狀態,只是建立了XMLHttpRequest對象,還未調用open()方法;
1:請求已開始,open()方法已調用,但還沒調用send()方法;
2:請求發送完成狀態,send()方法已調用;
3:開始讀取服務器響應;
4:讀取服務器響應結束。
onreadystatechange事件會在狀態爲一、二、三、4時引起。
下面代碼會被執行四次!對應XMLHttpRequest的四種狀態!
xmlHttp.onreadystatechange = function() { alert('hello'); };
但一般咱們只關心最後一種狀態,即讀取服務器響應結束時,客戶端纔會作出改變。咱們能夠經過XMLHttpRequest對象的readyState屬性來獲得XMLHttpRequest對象的狀態。
xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { alert('hello'); } };
其實咱們還要關心服務器響應的狀態碼xmlHttp.status是否爲200,其服務器響應爲404,或500,那麼就表示請求失敗了。咱們能夠經過XMLHttpRequest對象的status屬性獲得服務器的狀態碼。
最後,咱們還須要獲取到服務器響應的內容,能夠經過XMLHttpRequest對象的responseText獲得服務器響應內容。
xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { alert(xmlHttp.responseText); } };
須要注意的:
若是是post請求:
基於JS的ajax沒有Content-Type這個參數了,也就不會默認是urlencode這種形式了,須要咱們本身去設置
<1>須要設置請求頭:xmlHttp.setRequestHeader(「Content-Type」, 「application/x-www-form-urlencoded」);
注意 :form表單會默認這個鍵值對不設定,Web服務器會忽略請求體的內容。
<2>在發送時能夠指定請求體了:xmlHttp.send(「username=yuan&password=123」)
基於jQuery的ajax和form發送的請求,都會默認有Content-Type,默認urlencode,
Content-Type:客戶端告訴服務端我此次發送的數據是什麼形式的
dataType:客戶端指望服務端給我返回我設定的格式
若是是get請求:
xmlhttp.open("get","/sendAjax/?a=1&b=2");
小練習:和上面的練習同樣,只是換了一種方式(能夠和jQuery的對比一下)
<script> 方式一======================================= //基於JS實現實現用urlencode的方式 var ele_btn = document.getElementsByClassName("send_ajax")[0]; ele_btn.onclick = function () { //綁定事件 alert(5555); //發送ajax:有一下幾步 //(1)獲取XMLResquest對象 xmlhttp = new XMLHttpRequest(); //(2)鏈接服務器 //get請求的時候,必用send發數據,直接在請求路徑裏面發 {# xmlhttp.open("get","/sendAjax/?a=1&b=2");//open裏面的參數,請求方式,請求路徑#} //post請求的時候,須要用send發送數據 xmlhttp.open("post","/sendAjax/"); //設置請求頭的Content-Type xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //(3)發送數據 var ele_num1 = document.getElementsByClassName("num1")[0]; var ele_num2 = document.getElementsByClassName("num2")[0]; var ele_ret = document.getElementsByClassName("ret")[0]; var ele_scrf = document.getElementsByName("csrfmiddlewaretoken")[0]; var s1 = "num1="+ele_num1.value; var s2 = "num2="+ele_num2.value; var s3 = "&csrfmiddlewaretoken="+ele_scrf.value; xmlhttp.send(s1+"&"+s2+s3); //請求數據 //(4)回調函數,success xmlhttp.onreadystatechange = function () { if (this.readyState==4&&this.status==200){ alert(this.responseText); ele_ret.value = this.responseText } } }
方式二==================================================== {# ===================json=============#} var ele_btn=document.getElementsByClassName("send_ajax")[0]; ele_btn.onclick=function () { // 發送ajax // (1) 獲取 XMLHttpRequest對象 xmlHttp = new XMLHttpRequest(); // (2) 鏈接服務器 // get //xmlHttp.open("get","/sendAjax/?a=1&b=2"); // post xmlHttp.open("post","/sendAjax/"); // 設置請求頭的Content-Type var ele_csrf=document.getElementsByName("csrfmiddlewaretoken")[0]; xmlHttp.setRequestHeader("Content-Type","application/json"); xmlHttp.setRequestHeader("X-CSRFToken",ele_csrf.value); //利用js的方式避免forbidden的解決辦法 // (3) 發送數據 var ele_num1 = document.getElementsByClassName("num1")[0]; var ele_num2 = document.getElementsByClassName("num2")[0]; var ele_ret = document.getElementsByClassName("ret")[0]; var s1 = ele_num1.value; var s2 = ele_num2.value; xmlHttp.send(JSON.stringify( {"num1":s1,"num2":s2} )) ; // 請求體數據 // (4) 回調函數 success xmlHttp.onreadystatechange = function() { if(this.readyState==4 && this.status==200){ console.log(this.responseText); ele_ret.value = this.responseText } }; } </script>
def sendAjax(request): num1=request.POST.get("num1") num2 = request.POST.get("num2") ret = float(num1)+float(num2) return HttpResponse(ret)
JS實現ajax小結
建立XMLHttpRequest對象;
調用open()方法打開與服務器的鏈接;
調用send()方法發送請求;
爲XMLHttpRequest對象指定onreadystatechange事件函數,這個函數會在
XMLHttpRequest的一、二、三、4,四種狀態時被調用;
XMLHttpRequest對象的5種狀態,一般咱們只關心4狀態。
XMLHttpRequest對象的status屬性表示服務器狀態碼,它只有在readyState爲4時才能獲取到。
XMLHttpRequest對象的responseText屬性表示服務器響應內容,它只有在
readyState爲4時才能獲取到!
- 若是"Content-Type"="application/json",發送的數據是對象形式的{},須要在body裏面取數據,而後反序列化
= 若是"Content-Type"="application/x-www-form-urlencoded",發送的是/index/?name=haiyan&agee=20這樣的數據,
若是是POST請求須要在POST裏取數據,若是是GET,在GET裏面取數據
<h1>AJAX</h1> <button onclick="send()">測試</button> <div id="div1"></div> <script> function createXMLHttpRequest() { try { return new XMLHttpRequest();//大多數瀏覽器 } catch (e) { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { return new ActiveXObject("Microsoft.XMLHTTP"); } } } function send() { var xmlHttp = createXMLHttpRequest(); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { var div = document.getElementById("div1"); div.innerText = xmlHttp.responseText; div.textContent = xmlHttp.responseText; } }; xmlHttp.open("POST", "/ajax_post/", true); //post: xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.send(null); //post: xmlHttp.send("b=B"); } </script> #--------------------------------views.py from django.views.decorators.csrf import csrf_exempt def login(request): print('hello ajax') return render(request,'index.html') @csrf_exempt #csrf防護 def ajax_post(request): print('ok') return HttpResponse('helloyuanhao')
實例(用戶名是否已被註冊)
功能介紹
在註冊表單中,當用戶填寫了用戶名後,把光標移開後,會自動向服務器發送異步請求。服務器返回true或false,返回true表示這個用戶名已經被註冊過,返回false表示沒有註冊過。
客戶端獲得服務器返回的結果後,肯定是否在用戶名文本框後顯示「用戶名已被註冊」的錯誤信息!
案例分析
頁面中給出註冊表單;
在username表單字段中添加onblur事件,調用send()方法;
send()方法獲取username表單字段的內容,向服務器發送異步請求,參數爲username;
django 的視圖函數:獲取username參數,判斷是否爲「yuan」,若是是響應true,不然響應false
script type="text/javascript"> function createXMLHttpRequest() { try { return new XMLHttpRequest(); } catch (e) { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { return new ActiveXObject("Microsoft.XMLHTTP"); } } } function send() { var xmlHttp = createXMLHttpRequest(); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { if(xmlHttp.responseText == "true") { document.getElementById("error").innerText = "用戶名已被註冊!"; document.getElementById("error").textContent = "用戶名已被註冊!"; } else { document.getElementById("error").innerText = ""; document.getElementById("error").textContent = ""; } } }; xmlHttp.open("POST", "/ajax_check/", true, "json"); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var username = document.getElementById("username").value; xmlHttp.send("username=" + username); } </script> //--------------------------------------------------index.html <h1>註冊</h1> <form action="" method="post"> 用戶名:<input id="username" type="text" name="username" onblur="send()"/><span id="error"></span><br/> 密 碼:<input type="text" name="password"/><br/> <input type="submit" value="註冊"/> </form> //--------------------------------------------------views.py from django.views.decorators.csrf import csrf_exempt def login(request): print('hello ajax') return render(request,'index.html') # return HttpResponse('helloyuanhao') @csrf_exempt def ajax_check(request): print('ok') username=request.POST.get('username',None) if username=='yuan': return HttpResponse('true') return HttpResponse('false')
同源策略(Same origin policy)是一種約定,它是瀏覽器最核心也最基本的安全功能,若是缺乏了同源策略,則瀏覽器的正常功能可能都會受到影響。能夠說Web是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現。
同源策略,它是由Netscape提出的一個著名的安全策略。如今全部支持JavaScript 的瀏覽器都會使用這個策略。所謂同源是指,域名,協議,端口相同。當一個瀏覽器的兩個tab頁中分別打開來 百度和谷歌的頁面當瀏覽器的百度tab頁執行一個腳本的時候會檢查這個腳本是屬於哪一個頁面的,即檢查是否同源,只有和百度同源的腳本纔會被執行。若是非同源,那麼在請求數據時,瀏覽器會在控制檯中報一個異常,提示拒絕訪問。
jsonp(jsonpadding)
以前發ajax的時候都是在本身給本身的當前的項目下發
如今咱們來實現跨域發。給別人的項目發數據,
示例,先來測試一下
項目1:
==================================================8001項目的index <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <button>ajax</button> {% csrf_token %} <script> $("button").click(function(){ $.ajax({ url:"http://127.0.0.1:7766/SendAjax/", type:"POST", data:{"username":"yuan","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()}, success:function(data){ alert(123); alert(data) } }) }) </script> </body> </html> ==================================:8001項目的views def index(request): return render(request,"index.html") def ajax(request): import json print(request.POST,"+++++++++++") return HttpResponse(json.dumps("hello"))
項目2:
==================================:8002項目的index <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <button>sendAjax</button> {% csrf_token %} <script> $("button").click(function(){ $.ajax({ url:"/SendAjax/", type:"POST", data:{"username":"yuan","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()}, success:function(data){ alert(data) } }) }) </script> </body> </html> ==================================:8002項目的views def index(request): return render(request,"index.html") from django.views.decorators.csrf import csrf_exempt @csrf_exempt def SendAjax(request): import json print("++++++++") return HttpResponse(json.dumps("hello2"))
當點擊項目1的按鈕時,發送了請求,可是會發現報錯以下:
已攔截跨源請求:同源策略禁止讀取位於 http://127.0.0.1:7766/SendAjax/ 的遠程資源。(緣由:CORS 頭缺乏 'Access-Control-Allow-Origin')。
可是注意,項目2中的訪問已經發生了,說明是瀏覽器對非同源請求返回的結果作了攔截。
注意:a標籤,form,img標籤,引用cdn的css等也屬於跨域(跨不一樣的域拿過來文件來使用),不是全部的請求都給作跨域,(爲何要進行跨域呢?由於我想用人家的數據,因此得去別人的url中去拿,藉助script標籤)
<script src="http://127.0.0.1:8002/ajax_send2/"> 項目二 </script>
只有發ajax的時候給攔截了,因此要解決的問題只是針對ajax請求可以實現跨域請求
解決同源策源的兩個方法:
<script src="http://code.jquery.com/jquery-latest.js"></script>
藉助script標籤,實現跨域請求,示例:
8001/index
<button>ajax</button> {% csrf_token %} <script> function func(name){ alert(name) } </script> <script src="http://127.0.0.1:7766/SendAjax/"></script> # =============================:8002/ from django.views.decorators.csrf import csrf_exempt @csrf_exempt def SendAjax(request): import json print("++++++++") # dic={"k1":"v1"} return HttpResponse("func('yuan')") # return HttpResponse("func('%s')"%json.dumps(dic))
這其實就是JSONP的簡單實現模式,或者說是JSONP的原型:建立一個回調函數,而後在遠程服務上調用這個函數而且將JSON 數據形式做爲參數傳遞,完成回調。
將JSON數據填充進回調函數,這就是JSONP的JSON+Padding的含義。
可是以上的方式也有不足,回調函數的名字和返回的那個名字的一致。而且通常狀況下,咱們但願這個script標籤可以動態的調用,而不是像上面由於固定在html裏面因此沒等頁面顯示就執行了,很不靈活。咱們能夠經過javascript動態的建立script標籤,這樣咱們就能夠靈活調用遠程服務了。
解決辦法:javascript動態的建立script標籤
<button onclick="f()">sendAjax</button> <script> function addScriptTag(src){ var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); document.body.removeChild(script); } function func(name){ alert("hello"+name) } function f(){ addScriptTag("http://127.0.0.1:7766/SendAjax/") } </script>
爲了更加靈活,如今將你本身在客戶端定義的回調函數的函數名傳送給服務端,服務端則會返回以你定義的回調函數名的方法,將獲取的json數據傳入這個方法完成回調:
將8001的f()改寫爲:
function f(){ addScriptTag("http://127.0.0.1:7766/SendAjax/?callbacks=func") }
8002的views改成:
def SendAjax(request): import json dic={"k1":"v1"} print("callbacks:",request.GET.get("callbacks")) callbacks=request.GET.get("callbacks") #注意要在服務端獲得回調函數名的名字 return HttpResponse("%s('%s')"%(callbacks,json.dumps(dic)))
jQuery對JSONP的實現
getJSON
jQuery框架也固然支持JSONP,可使用$.getJSON(url,[data],[callback])方法
8001的html改成:
<button onclick="f()">sendAjax</button> <script> function f(){ $.getJSON("http://127.0.0.1:7766/SendAjax/?callbacks=?",function(arg){ alert("hello"+arg) }); } </script>
8002的views不改動。
結果是同樣的,要注意的是在url的後面必須添加一個callback參數,這樣getJSON方法纔會知道是用JSONP方式去訪問服務,callback後面的那個問號是內部自動生成的一個回調函數名。
此外,若是說咱們想指定本身的回調函數名,或者說服務上規定了固定回調函數名該怎麼辦呢?咱們可使用$.ajax方法來實現
8001的html改成:
<script> function f(){ $.ajax({ url:"http://127.0.0.1:7766/SendAjax/", dataType:"jsonp", jsonp: 'callbacks', jsonpCallback:"SayHi" }); } function SayHi(arg){ alert(arg); } </script>
8002的views不改動。
固然,最簡單的形式仍是經過回調函數來處理:
<script> function f(){ $.ajax({ url:"http://127.0.0.1:7766/SendAjax/", dataType:"jsonp", //必須有,告訴server,此次訪問要的是一個jsonp的結果。 jsonp: 'callbacks', //jQuery幫助隨機生成的:callbacks="wner" success:function(data){ alert("hi "+data) } }); } </script>
jsonp: 'callbacks'就是定義一個存放回調函數的鍵,jsonpCallback是前端定義好的回調函數方法名'SayHi',server端接受callback鍵對應值後就能夠在其中填充數據打包返回了;
jsonpCallback參數能夠不定義,jquery會自動定義一個隨機名發過去,那前端就得用回調函數來處理對應數據了。利用jQuery能夠很方便的實現JSONP來進行跨域訪問。
注意 JSONP必定是GET請求
應用
<input type="button" onclick="AjaxRequest()" value="跨域Ajax" /> <div id="container"></div> <script type="text/javascript"> function AjaxRequest() { $.ajax({ url: 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403', type: 'GET', dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'list', success: function (data) { $.each(data.data,function(i){ var item = data.data[i]; var str = "<p>"+ item.week +"</p>"; $('#container').append(str); $.each(item.list,function(j){ var temp = "<a href='" + item.list[j].link +"'>" + item.list[j].name +" </a><br/>"; $('#container').append(temp); }); $('#container').append("<hr/>"); }) } }); } </script>