同源策略(Same origin policy)是一種約定,它是瀏覽器最核心也最基本的安全功能,若是缺乏了同源策略,則瀏覽器的正常功能可能都會受到影響。能夠說Web是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現。javascript
==================================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的按鈕時,發送了請求,可是會發現火狐瀏覽器報錯以下html
已攔截跨源請求:同源策略禁止讀取位於 http://127.0.0.1:7766/SendAjax/ 的遠程資源。(緣由:CORS 頭缺乏 'Access-Control-Allow-Origin')。
解決方案1:前端
藉助scrip標籤,實現跨域請求,示例:java
# =============================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數據做爲參數傳遞,完成回調。jquery
將JSON數據填充進入回調函數,這就是JSON的JSON+Padding的含義。ajax
通常狀況下,咱們但願這個script標籤可以動態的調用,而不是像上面由於固定在html裏面因此沒等頁面顯示就執行了,很不靈活。咱們能夠經過javascript動態的建立script標籤,這樣咱們就能夠靈活調用遠程服務了。django
<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數據傳入這個方法完成回調: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(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請求