一 AJAX預備知識:json進階
1.1 什麼是JSON?
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。JSON是用字符串來表示Javascript對象;javascript
請你們記住一句話:json字符串就是js對象的一種表現形式(字符串的形式)html
既然咱們已經學過python的json模塊,咱們就用它來測試下json字符串和json對象究竟是什麼前端
![](http://static.javashuo.com/static/loading.gif)
import json i=10 s='hello' t=(1,4,6) l=[3,5,7] d={'name':"yuan"} json_str1=json.dumps(i) json_str2=json.dumps(s) json_str3=json.dumps(t) json_str4=json.dumps(l) json_str5=json.dumps(d) print(json_str1) #'10' print(json_str2) #'"hello"' print(json_str3) #'[1, 4, 6]' print(json_str4) #'[3, 5, 7]' print(json_str5) #'{"name": "yuan"}'
這裏面的json_str就是json字符串;java
那麼json字符串裏均可以放哪些值呢?python
JSON字符串內的值:jquery
- 數字 (整數或浮點數)
- 字符串 (在雙引號中)
- 邏輯值 (true 或 false)
- 數組 (在方括號中)
- 對象 (在花括號中,引號用雙引)
- null
看着是否是有點眼熟啊,對了,這就是我們js的數據對象;無論是python仍是其它語言,它們都有本身的數據類型,但若是要處理成json字符串那麼,就要把數據換轉成js對應的數據對象(好比python的元組就被處理成了數組,字典就被處理成object),再加上引號就是我們的json字符串了;
前端接受到json字符串,就能夠經過JSON.parse()等方法解析成json對象(即js對象)直接使用了。ajax
之因此稱json對象爲js的子集,是由於像undefined,NaN,{'name':'yuan'}等都不在json對象的範疇。django
1.2 python與json對象的對應:
![](http://static.javashuo.com/static/loading.gif)
python --> json
dict object
list,tuple array
str,unicode string
int,long,float number
True true
False false
None null
讓咱們看一個帶方法的json對象:json
![](http://static.javashuo.com/static/loading.gif)
var person = {"name":"alex", "sex":"men", "teacher":{ "name":"tiechui", "sex":"half_men", }, "bobby":['basketball','running'], "getName":function() {return 80;} }; alert(person.name); alert(person.getName()); alert(person.teacher.name); alert(person.bobby[0]);
person是一個json對象,由於它知足json規範:在json六大範疇且引號雙引!後端
1.3 .parse()和.stringify()
![](http://static.javashuo.com/static/loading.gif)
parse() 用於從一個json字符串中解析出json對象,如 var str = '{"name":"yuan","age":"23"}' 結果:JSON.parse(str) ------> Object {age: "23",name: "yuan"} stringify()用於從一個json對象解析成json字符串,如 var c= {a:1,b:2} 結果: JSON.stringify(c) ------> '{"a":1,"b":2}' 注意1:單引號寫在{}外,每一個屬性名都必須用雙引號,不然會拋出異常。 注意2: a={name:"yuan"}; //ok b={'name':'yuan'}; //ok c={"name":"yuan"}; //ok alert(a.name); //ok alert(a[name]); //undefined alert(a['name']) //ok
1.4 django向js發送數據
![](http://static.javashuo.com/static/loading.gif)
def login(request): obj={'name':"alex111"} return render(request,'index.html',{"objs":json.dumps(obj)}) #---------------------------------- <script> var temp={{ objs|safe }} alert(temp.name); alert(temp['name']) </script>
此外,還能夠經過下面介紹的ajax技術使js接受django相應的json數據。
1.5 JSON與XML比較
- 可讀性: XML勝出;
- 解碼難度:JSON自己就是JS對象(主場做戰),因此簡單不少;
- 流行度: XML已經流行好多年,但在AJAX領域,JSON更受歡迎。
註解:其實本沒什麼json對象,只是咱們本身這麼稱呼罷了,所謂的json數據就是指json字符串,在前端解析出來的對象就是js對象的一部分!
二 什麼是AJAX
AJAX(Asynchronous Javascript And XML)翻譯成中文就是「異步Javascript和XML」。即便用Javascript語言與服務器進行異步交互,傳輸的數據爲XML(固然,傳輸的數據不僅是XML)。
- 同步交互:客戶端發出一個請求後,須要等待服務器響應結束後,才能發出第二個請求;
- 異步交互:客戶端發出一個請求後,無需等待服務器響應結束,就能夠發出第二個請求。
AJAX除了異步的特色外,還有一個就是:瀏覽器頁面局部刷新;(這一特色給用戶的感覺是在不知不覺中完成請求和響應過程)
![](http://static.javashuo.com/static/loading.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> window.onload = function() {//當文檔加載完畢時執行本函數 var form = document.getElementById("form1");//獲取表單元素對象 form.onsubmit = function() {//給表單元素添加一個監聽,監聽表單被提交事件 var usernameValue = form.username.value;//獲取表單中名爲username的表單元素值 if(!usernameValue) {//判斷該值是否爲空 var usernameSpan = document.getElementById("usernameSpan");//獲得usernmae元素後的<span>元素 usernameSpan.innerText = "用戶名不能爲空!";//設置span元素內容! return false;//返回false,表示攔截了表單提交動做 } return true;//不攔截表單提交動做 }; }; </script> </head> <body> <h1>註冊頁面</h1> <form action="" method="post" id="form1"> 用戶名:<input type="text" name="username"/> <span id="usernameSpan"></span> <br/> 密 碼:<input type="password" name="password"/> <span id="passwordSpan"></span> <br/> <input type="submit" value="註冊"/> </form> </body> </html>
三 AJAX常見應用情景
當咱們在百度中輸入一個「老」字後,會立刻出現一個下拉列表!列表中顯示的是包含「傳」字的4個關鍵字。
其實這裏就使用了AJAX技術!當文件框發生了輸入變化時,瀏覽器會使用AJAX技術向服務器發送一個請求,查詢包含「傳」字的前10個關鍵字,而後服務器會把查詢到的結果響應給瀏覽器,最後瀏覽器把這4個關鍵字顯示在下拉列表中。
- 整個過程當中頁面沒有刷新,只是刷新頁面中的局部位置而已!
- 當請求發出後,瀏覽器還能夠進行其餘操做,無需等待服務器的響應!
當輸入用戶名後,把光標移動到其餘表單項上時,瀏覽器會使用AJAX技術向服務器發出請求,服務器會查詢名爲zhangSan的用戶是否存在,最終服務器返回true表示名爲lemontree7777777的用戶已經存在了,瀏覽器在獲得結果後顯示「用戶名已被註冊!」。
四 AJAX的優缺點
優勢:
- AJAX使用Javascript技術向服務器發送異步請求;
- AJAX無須刷新整個頁面(局部刷新);
- 由於服務器響應內容再也不是整個頁面,而是頁面中的局部,因此AJAX性能高;
缺點:
- AJAX並不適合全部場景,不少時候仍是要使用同步交互;
- AJAX雖然提升了用戶體驗,但無形中向服務器發送的請求次數增多了,致使服務器壓力增大;
- 由於AJAX是在瀏覽器中使用Javascript技術完成的,因此還須要處理瀏覽器兼容性問題;
五 AJAX技術
四步操做:
- 建立核心對象;
- 使用核心對象打開與服務器的鏈接;
- 發送請求
- 註冊監聽,監聽服務器響應。
XMLHTTPRequest
- open(請求方式, URL, 是否異步)
- send(請求體)
- onreadystatechange,指定監聽函數,它會在xmlHttp對象的狀態發生變化時被調用
- readyState,當前xmlHttp對象的狀態,其中4狀態表示服務器響應結束
- status:服務器響應的狀態碼,只有服務器響應結束時纔有這個東東,200表示響應成功;
- responseText:獲取服務器的響應體
六 AJAX實現
6.1 準備工做(後臺設定):
1 def login(request): 2 print('hello ajax') 3 return render(request,'index.html') 4 5 def ajax_get(request): 6 return HttpResponse('hello 你好')
6.2 AJAX核心(XMLHttpRequest)
其實AJAX就是在Javascript中多添加了一個對象:XMLHttpRequest對象。全部的異步交互都是使用XMLHttpServlet對象完成的。也就是說,咱們只須要學習一個Javascript的新對象便可。
var xmlHttp = new XMLHttpRequest();(大多數瀏覽器都支持DOM2規範)
注意,各個瀏覽器對XMLHttpRequest的支持也是不一樣的!爲了處理瀏覽器兼容問題,給出下面方法來建立XMLHttpRequest對象:
![](http://static.javashuo.com/static/loading.gif)
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; }
6.3 打開與服務器的鏈接(open方法)
當獲得XMLHttpRequest對象後,就能夠調用該對象的open()方法打開與服務器的鏈接了。open()方法的參數以下:
open(method, url, async):
- method:請求方式,一般爲GET或POST;
- url:請求的服務器地址,例如:/ajaxdemo1/AServlet,若爲GET請求,還能夠在URL後追加參數;
- async:這個參數能夠不給,默認值爲true,表示異步請求;
var xmlHttp = createXMLHttpRequest(); xmlHttp.open("GET", "/ajax_get/", true);
6.4 發送請求
當使用open打開鏈接後,就能夠調用XMLHttpRequest對象的send()方法發送請求了。send()方法的參數爲POST請求參數,即對應HTTP協議的請求體內容,如果GET請求,須要在URL後鏈接參數。
注意:若沒有參數,須要給出null爲參數!若不給出null爲參數,可能會致使FireFox瀏覽器不能正常發送請求!
xmlHttp.send(null);
6.5 接收服務器響應
當請求發送出去後,服務器端Servlet就開始執行了,但服務器端的響應尚未接收到。接下來咱們來接收服務器的響應。
XMLHttpRequest對象有一個onreadystatechange事件,它會在XMLHttpRequest對象的狀態發生變化時被調用。下面介紹一下XMLHttpRequest對象的5種狀態:
- 0:初始化未完成狀態,只是建立了XMLHttpRequest對象,還未調用open()方法;
- 1:請求已開始,open()方法已調用,但還沒調用send()方法;
- 2:請求發送完成狀態,send()方法已調用;
- 3:開始讀取服務器響應;
- 4:讀取服務器響應結束。
onreadystatechange事件會在狀態爲1、2、3、4時引起。
下面代碼會被執行四次!對應XMLHttpRequest的四種狀態!
xmlHttp.onreadystatechange = function() { alert('hello'); };
但一般咱們只關心最後一種狀態,即讀取服務器響應結束時,客戶端纔會作出改變。咱們能夠經過XMLHttpRequest對象的readyState屬性來獲得XMLHttpRequest對象的狀態。
xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { alert('hello'); } };
其實咱們還要關心服務器響應的狀態碼是否爲200,其服務器響應爲404,或500,那麼就表示請求失敗了。咱們能夠經過XMLHttpRequest對象的status屬性獲得服務器的狀態碼。
最後,咱們還須要獲取到服務器響應的內容,能夠經過XMLHttpRequest對象的responseText獲得服務器響應內容。
xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { alert(xmlHttp.responseText); } };
6.6 if 發送POST請求:
<1>須要設置請求頭:xmlHttp.setRequestHeader(「Content-Type」, 「application/x-www-form-urlencoded」);
注意 :form表單會默認這個鍵值對;不設定,Web服務器會忽略請求體的內容。
<2>在發送時能夠指定請求體了:xmlHttp.send(「username=yuan&password=123」)
6.7 AJAX實現小結
建立XMLHttpRequest對象; 調用open()方法打開與服務器的鏈接; 調用send()方法發送請求; 爲XMLHttpRequest對象指定onreadystatechange事件函數,這個函數會在 XMLHttpRequest的一、二、三、4,四種狀態時被調用; XMLHttpRequest對象的5種狀態,一般咱們只關心4狀態。 XMLHttpRequest對象的status屬性表示服務器狀態碼,它只有在readyState爲4時才 能獲取到。 XMLHttpRequest對象的responseText屬性表示服務器響應內容,它只有在 readyState爲4時才能獲取到!
6.8 請求完整代碼:
![](http://static.javashuo.com/static/loading.gif)
<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')
思考:啓動後臺後,直接運行html,會怎麼樣?這就涉及到我們一會要講到的同源策略機制和跨域請求;
七 AJAX實例(用戶名是否已被註冊)
7.1 功能介紹
在註冊表單中,當用戶填寫了用戶名後,把光標移開後,會自動向服務器發送異步請求。服務器返回true或false,返回true表示這個用戶名已經被註冊過,返回false表示沒有註冊過。
客戶端獲得服務器返回的結果後,肯定是否在用戶名文本框後顯示「用戶名已被註冊」的錯誤信息!
7.2 案例分析
- 頁面中給出註冊表單;
- 在username表單字段中添加onblur事件,調用send()方法;
- send()方法獲取username表單字段的內容,向服務器發送異步請求,參數爲username;
- django 的視圖函數:獲取username參數,判斷是否爲「yuan」,若是是響應true,不然響應false
7.3 代碼
![](http://static.javashuo.com/static/loading.gif)
<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')
八 jquery實現的ajax
8.1 快捷API:
![](http://static.javashuo.com/static/loading.gif)
<1>$.get(url, [data], [callback], [type]) <2>$.post(url, [data], [callback], [type]) //type: text|html|json|script 應用: //請求參數應該儘可能放在data參數中,由於能夠自動編碼,手動拼接url要注意編碼問題 function testWithDataAndCallback() { //$.post... $.get('/user/list', {type: 1}, function (data, callbacktype, jqXHR) { console.log(data);//將json字符串解析成json對象 }); } -------------- <3>$.getScript()使用 AJAX 請求,獲取和運行 JavaScript: 應用: function testGetScript() { // alert(testFun(3, 4)); $.getScript('test.js', function () { alert(add(1, 6)); }); } // test.js function add(a,b){ return a+b } <4>$.getJSON() 與$.get()是同樣的,只不過就是作後一個參數type必須是json數據了。通常同域操做用$.get()就能夠,$.getJson 最主要是用來進行jsonp跨域操做的。
8.2 核心API的基本使用:
![](http://static.javashuo.com/static/loading.gif)
<1> $.ajax的兩種寫法: $.ajax("url",{}) $.ajax({}) <2> $.ajax的基本使用 $.ajax({ url:"//", data:{a:1,b:2}, type:"GET", success:function(){} }) <3> 回調函數 $.ajax('/user/allusers', { success: function (data) { console.log(arguments); }, error: function (jqXHR, textStatus, err) { // jqXHR: jQuery加強的xhr // textStatus: 請求完成狀態 // err: 底層經過throw拋出的異常對象,值與錯誤類型有關 console.log(arguments); }, complete: function (jqXHR, textStatus) { // jqXHR: jQuery加強的xhr // textStatus: 請求完成狀態 success | error console.log('statusCode: %d, statusText: %s', jqXHR.status, jqXHR.statusText); console.log('textStatus: %s', textStatus); }, statusCode: { '403': function (jqXHR, textStatus, err) { console.log(arguments); //注意:後端模擬errror方式:HttpResponse.status_code=500 }, '400': function () { } } });
8.3 核心API的重要字段(參數):
![](http://static.javashuo.com/static/loading.gif)
<1> ----------請求數據相關: data, processData, contentType, traditional-------------- data: 當前ajax請求要攜帶的數據,是一個json的object對象,ajax方法就會默認地把它編碼成某種格式 (urlencoded:?a=1&b=2)發送給服務端;此外,ajax默認以get方式發送請求。 # function testData() { # $.ajax("/test",{ //此時的data是一個json形式的對象 # data:{ # a:1, # b:2 # } # }); //?a=1&b=2 processData:聲明當前的data數據是否進行轉碼或預處理,默認爲true,即預處理;if爲false, # 那麼對data:{a:1,b:2}會調用json對象的toString()方法,即{a:1,b:2}.toString() # ,最後獲得一個[object,Object]形式的結果。 # {"1":"111","2":"222","3":"333"}.toString();//[object Object] # 該屬性的意義在於,當data是一個dom結構或者xml數據時,咱們但願數據不要進行處理,直接發過去, # 就能夠講其設爲true。 contentType:默認值: "application/x-www-form-urlencoded"。發送信息至服務器時內容編碼類型。 # 用來指明當前請求的數據編碼格式;urlencoded:?a=1&b=2;若是想以其餘方式提交數據, # 好比contentType:"application/json",即向服務器發送一個json字符串: # $.ajax("/ajax_get",{ # # data:JSON.stringify({ # a:22, # b:33 # }), # contentType:"application/json", # type:"POST", # # }); //{a: 22, b: 33} # 注意:contentType:"application/json"一旦設定,data必須是json字符串,不能是json對象 traditional:通常是咱們的data數據有數組時會用到 :data:{a:22,b:33,c:["x","y"]}, traditional爲false會對數據進行深層次迭代; <2> ------------------------ 響應數據: dataType、dataFilter------------------------ dataType:預期服務器返回的數據類型,服務器端返回的數據會根據這個值解析後,傳遞給回調函數。 # 默認不須要顯性指定這個屬性,ajax會根據服務器返回的content Type來進行轉換;好比咱們的服務器響應的 # content Type爲json格式,這時ajax方法就會對響應的內容進行一個json格式的轉換,if轉換成功,咱們在 # success的回調函數裏就會獲得一個json格式的對象;轉換失敗就會觸發error這個回調函數。若是咱們明確地指 # 定目標類型,就可使用data Type。 # dataType的可用值:html|xml|json|text|script # 見下dataType實例 dataFilter: 類型:Function 給 Ajax返回的原始數據的進行預處理的函數。見下dataFilter實例 <3> 請求類型 type: 類型:String 默認值: "GET")。請求方式 ("POST" 或 "GET"), 默認爲 "GET"。注意:其它 HTTP 請求方法, 如 PUT 和 DELETE 也可使用,但僅部分瀏覽器支持。 <4> 前置處理 beforeSend(XHR) 類型:Function 發送請求前可修改 XMLHttpRequest 對象的函數,如添加自定義 HTTP 頭。XMLHttpRequest # 對象是惟一的參數。這是一個 Ajax 事件。若是返回 false 能夠取消本次 ajax 請求。 # 見下beforeSend實例 <5> jsonp 類型:String # 在一個 jsonp 請求中重寫回調函數的名字。這個值用來替代在 "callback=?" 這種 GET 或 POST 請求中 URL # 參數裏的 "callback" 部分,好比 {jsonp:'onJsonPLoad'} 會致使將 "onJsonPLoad=?" 傳給服務器。 <6> jsonpCallback 類型:String # 爲 jsonp 請求指定一個回調函數名。這個值將用來取代 jQuery 自動生成的隨機函數名。這主要用來讓 jQuery 生 # 成度獨特的函數名,這樣管理請求更容易,也能方便地提供回調函數和錯誤處理。你也能夠在想讓瀏覽器緩存 GET 請求 # 的時候,指定這個回調函數名。
8.4 實例代碼
![](http://static.javashuo.com/static/loading.gif)
from django.shortcuts import render,HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. import json def login(request): return render(request,'Ajax.html') def ajax_get(request): l=['alex','little alex'] dic={"name":"alex","pwd":123} #return HttpResponse(l) #元素直接轉成字符串alexlittle alex #return HttpResponse(dic) #字典的鍵直接轉成字符串namepwd return HttpResponse(json.dumps(l)) return HttpResponse(json.dumps(dic))# 傳到前端的是json字符串,要想使用,須要JSON.parse(data) //--------------------------------------------------- function testData() { $.ajax('ajax_get', { success: function (data) { console.log(data); console.log(typeof(data)); //console.log(data.name); //JSON.parse(data); //console.log(data.name); }, //dataType:"json", } )} 註解:Response Headers的content Type爲text/html,因此返回的是String;但若是咱們想要一個json對象 設定dataType:"json"便可,至關於告訴ajax方法把服務器返回的數據轉成json對象發送到前端.結果爲object 固然, return HttpResponse(json.dumps(a),content_type="application/json") 這樣就不須要設定dataType:"json"了。 content_type="application/json"和content_type="json"是同樣的! dataType
![](http://static.javashuo.com/static/loading.gif)
function testData() { $.ajax('ajax_get', { success: function (data) { console.log(data); }, dataType: 'json', dataFilter: function(data, type) { console.log(data);//["alex", "little alex"] console.log(type);//json //var tmp = JSON.parse(data); return tmp.length;//2 } });} dataFilter實例
![](http://static.javashuo.com/static/loading.gif)
function testData() { $.ajax('ajax_get', { beforeSend: function (jqXHR, settings) { console.log(arguments); console.log('beforeSend'); jqXHR.setRequestHeader('test', 'haha'); jqXHR.testData = {a: 1, b: 2}; }, success: function (data) { console.log(data); }, complete: function (xhr) { console.log(xhr); console.log(xhr.testData); }, })}; beforeSend實例
8.5 csrf跨站請求僞造
$.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' }, });
九 跨域請求
9.1 同源策略機制
瀏覽器有一個很重要的概念——同源策略(Same-Origin Policy)。所謂同源是指,域名,協議,端口相同。不一樣源的客戶端腳本(javascript、ActionScript)在沒明確受權的狀況下,不能讀寫對方的資源。
簡單的來講,瀏覽器容許包含在頁面A的腳本訪問第二個頁面B的數據資源,這一切是創建在A和B頁面是同源的基礎上。
若是Web世界沒有同源策略,當你登陸淘寶帳號並打開另外一個站點時,這個站點上的JavaScript能夠跨域讀取你的淘寶帳號數據,這樣整個Web世界就無隱私可言了。
9.2 jsonp的js實現
JSONP是JSON with Padding的略稱。可讓網頁從別的域名(網站)那獲取資料,即跨域讀取數據。
它是一個非官方的協議,它容許在服務器端集成Script tags返回至客戶端,經過javascript callback的形式實現跨域訪問(這僅僅是JSONP簡單的實現形式)。
JSONP就像是JSON+Padding同樣(Padding這裏咱們理解爲填充)
實例:
![](http://static.javashuo.com/static/loading.gif)
#---------------------------http://127.0.0.1:8001/login def login(request): print('hello ajax') return render(request,'index.html') #---------------------------返回用戶的index.html <h1>發送JSONP數據</h1> <script> function fun1(arg){ alert("hello"+arg) } </script> <script src="http://127.0.0.1:8002/get_byjsonp/"></script> //返回:<script>fun1("yuan")</script> #-----------------------------http://127.0.0.1:8002/get_byjsonp def get_byjsonp(req): print('8002...') return HttpResponse('fun1("此處爲padding 手動滑稽")')
這其實就是JSONP的簡單實現模式,或者說是JSONP的原型:建立一個回調函數,而後在遠程服務上調用這個函數而且將JSON 數據形式做爲參數傳遞,完成回調。
將JSON數據填充進回調函數,這應該就是JSONP的JSON+Padding的含義吧。
通常狀況下,咱們但願這個script標籤可以動態的調用,而不是像上面由於固定在html裏面因此沒等頁面顯示就執行了,很不靈活。咱們能夠經過javascript動態的建立script標籤,這樣咱們就能夠靈活調用遠程服務了。
![](http://static.javashuo.com/static/loading.gif)
<button onclick="f()">submit</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 fun1(arg){ alert("hello"+arg) } function f(){ addScriptTag("http://127.0.0.1:8002/get_byjsonp/") } </script>
爲了更加靈活,如今將你本身在客戶端定義的回調函數的函數名傳送給服務端,服務端則會返回以你定義的回調函數名的方法,將獲取的json數據傳入這個方法完成回調:
![](http://static.javashuo.com/static/loading.gif)
<button onclick="f()">submit</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 SayHi(arg){ alert("Hello "+arg) } function f(){ addScriptTag("http://127.0.0.1:8002/get_byjsonp/?callbacks=SayHi") } </script> ----------------------views.py def get_byjsonp(req): func=req.GET.get("callbacks") return HttpResponse("%s('yuan')"%func)
11.3 jQuery對JSONP的實現
jQuery框架也固然支持JSONP,可使用$.getJSON(url,[data],[callback])方法
![](http://static.javashuo.com/static/loading.gif)
<script type="text/javascript"> $.getJSON("http://127.0.0.1:8002/get_byjsonp?callback=?",function(arg){ alert("hello"+arg) }); </script>
結果是同樣的,要注意的是在url的後面必須添加一個callback參數,這樣getJSON方法纔會知道是用JSONP方式去訪問服務,callback後面的那個問號是內部自動生成的一個回調函數名。
此外,若是說咱們想指定本身的回調函數名,或者說服務上規定了固定回調函數名該怎麼辦呢?咱們可使用$.ajax方法來實現
![](http://static.javashuo.com/static/loading.gif)
<script type="text/javascript" src="/static/jquery-2.2.3.js"></script> <script type="text/javascript"> $.ajax({ url:"http://127.0.0.1:8002/get_byjsonp", dataType:"jsonp", jsonp: 'callbacks', jsonpCallback:"SayHi" }); function SayHi(arg){ alert(arg); } </script> #--------------------------------- http://127.0.0.1:8002/get_byjsonp def get_byjsonp(req): callback=req.GET.get('callbacks') print(callback) return HttpResponse('%s("yuan")'%callback)
固然,最簡單的形式仍是經過回調函數來處理:(推薦)
![](http://static.javashuo.com/static/loading.gif)
<script type="text/javascript" src="/static/jquery-2.2.3.js"></script> <script type="text/javascript"> $.ajax({ url:"http://127.0.0.1:8002/get_byjsonp", dataType:"jsonp", //必須有,告訴server,此次訪問要的是一個jsonp的結果。 jsonp: 'callbacks', //jQuery幫助隨機生成的:callbacks="wner" success:function(data){ alert(data) } }); </script> #-------------------------------------http://127.0.0.1:8002/get_byjsonp def get_byjsonp(req): callbacks=req.GET.get('callbacks') print(callbacks) #wner return HttpResponse("%s('yuan')"%callbacks)
jsonp: 'callbacks'就是定義一個存放回調函數的鍵,jsonpCallback是前端定義好的回調函數方法名'SayHi',server端接受callback鍵對應值後就能夠在其中填充數據打包返回了;
jsonpCallback參數能夠不定義,jquery會自動定義一個隨機名發過去,那前端就得用回調函數來處理對應數據了。
利用jQuery能夠很方便的實現JSONP來進行跨域訪問。
註解1: JSONP必定是GET請求
註解2:
![](http://static.javashuo.com/static/loading.gif)
<button onclick="f()">submit</button> <script src="/static/jquery-1.8.2.min.js"></script> <script type="text/javascript"> function f(){ $.ajax({ url:"http://127.0.0.1:8002/get_byjsonp", dataType:"jsonp", jsonp: 'callbacks', success :function(data){ //傳過來的數據會被轉換成js對象 console.log(data); //Object {name: Array[2]} console.log(typeof data); //object console.log(data.name) //["alex", "alvin"] } }); } </script> ---------------------------------------------views.py def get_byjsonp(req): func=req.GET.get("callbacks") a=json.dumps({'name':('alex','alvin')}) return HttpResponse("%s(%s)"%(func,a)) #return HttpResponse("%s({'name':('alex','alvin')})"%func) #return HttpResponse("%s('hello')"%func) #return HttpResponse("%s([12,34])"%func) #return HttpResponse("%s(5)"%func)
補充:
![](http://static.javashuo.com/static/loading.gif)
#views.py 中能夠用 request.is_ajax() 方法判斷是不是 ajax 請求,須要添加一個 HTTP 請求頭: #原生javascript: #xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); #用 jQuery: #用 $.ajax 方法代替 $.get,由於 $.get 在 IE 中不會發送 ajax header #注意:is_ajax()在跨域ajax請求時很差使
思考1:爲何該代碼在IE上會報錯?
思考2:這裏只是返回了一個"hello''的字符串,那麼jsonp可不能夠返回更多其它的數據類型呢,好比列表,字典等?