同源策略
同源策略(Same origin policy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會受到影響。可以說Web是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現。
==================================http://127.0.0.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> <script> $("button").click(function(){ $.ajax({ url:"http://127.0.0.1:7766/SendAjax/", type:"POST", data:{"username":"test","csrfmiddlewaretoken":'{{ csrf_token }}', success:function(data){ alert(123); alert(data) } }) }) </script> </body> </html> ==================================http://127.0.0.1:8001項目的views def index(request): return render(request,"index.html") def ajax(request): import json print(request.POST,"+++++++++++") return HttpResponse(json.dumps("hello"))
==================================http://127.0.0.1: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> ==================================http://127.0.0.1:8002項目的view視圖函數 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')。
解決方案1:
借助scrip標簽,實現跨域請求,示例:
# =============================http://127.0.0.1:8001/index <button>ajax</button> <script> function func(name){ alert(name) } </script> <script src="http://127.0.0.1:7766/SendAjax/"></script> # =============================http://127.0.0.1:8002/ # == view視圖函數
from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def SendAjax(request): print("++++++++") # dic={"k1":"v1"} return HttpResponse("func('yuan')") # return HttpResponse("func('%s')"%json.dumps(dic))
這就是JSONP的簡單實現模式,或者是JSONP的原型:創建一個回調函數,然后在遠程服務商調用這個函數,並件gJSON數據作為參數傳遞,完成回調。
將JSON數據填充進入回調函數,這就是JSON的JSON+Padding的含義。
一般情況下,我們希望這個script標簽能夠動態的調用,而不是像上面因為固定在html里面所以沒等頁面顯示就執行了,很不靈活。我們可以通過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方法來實現
$.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請求
應用
示例項目
