同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,若是缺乏了同源策略,则浏览器的正常功能可能都会受到影响。能够说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。html
=================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> {% csrf_token %} <script> $("button").click(function(){ $.ajax({ url:"http://127.0.0.1:8002/SendAjax/", type:"POST", data:{"username":"man","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()}, success:function(data){ alert(123); alert(data); } }) }) </script> </body> </html>
项目2前端
==================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":"man","csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()}, success:function(data){ alert(data) } }) }) </script> </body> </html> ===================http://127.0.0.1:8002项目的views==================== def index(request): return render(request,"index.html") from django.views.decorators.csrf import csrf_exempt @csrf_exempt def SendAjax(request): # 不校验csrf_token import json return HttpResponse(json.dumps("hello2"))
当点击项目1的按钮时,发送了请求,可是会发现报错以下:jquery
已拦截跨源请求:同源策略禁止读取位于 http://127.0.0.1:8002/SendAjax/ 的远程资源。(缘由:CORS 头缺乏 'Access-Control-Allow-Origin')
# =============================http://127.0.0.1:8001/index <button>ajax</button> {% csrf_token %} <script> function func(name){ alert(name) } </script> <script src="http://127.0.0.1:8002/SendAjax/"></script> # =============================http://127.0.0.1:8002/ from django.views.decorators.csrf import csrf_exempt @csrf_exempt def SendAjax(request): import json # dic={"k1":"v1"} return HttpResponse("func('param')") # return HttpResponse("func('%s')"%json.dumps(dic))
================http://127.0.0.1:8001/index=== <button class="get_index" onclick=f()>洗剪吹</button> <srcipt>
function ret(arg) {
console.log(arg)
}
$(".get_index").click(function () { $.ajax({ url:"http://127.0.0.1:8002/index/", type:"get", dataType:"jsonp", // 伪造ajax 基于script jsonp: 'callbacks', //jsonpCallback:"ret", success:function (data) { console.log(data) } }) }) </srcipt> =================127.0.0.1:8002/index==== def index(request): # jsonp func=request.GET.get("callbacks") # print("func",func) info={"name":"man","age":34,"price":200} return HttpResponse(" ('%s')"%(func,json.dumps(info)
jsonp: 'callbacks'就是定义一个存放回调函数的键,jsonpCallback是前端定义好的回调函数方法名'ret',server端接受callback键对应值后就能够在其中填充数据打包返回了; ajax
jsonpCallback参数能够不定义,jquery会自动定义一个随机名发过去,那前端就得用回调函数来处理对应数据了。利用jQuery能够很方便的实现JSONP来进行跨域访问。django
$(".get_index").click(function () { $.ajax({ url:"http://www.jxntv.cn/data/jmd-jxtv2.html", type:"get", dataType:"jsonp", // 伪造ajax 基于script jsonp: 'callbacks', jsonpCallback:"list", success:function (data) { //console.log(data.data); var html=""; $.each(data.data,function (index,weekday) { console.log(weekday); // {week: "周一", list: Array(19)} html+='<p>'+weekday.week+'</p>'; $.each(weekday.list,function (j,show) { html+= '<p><a href='+show.link+'>'+show.name+'</a></p>' }) }); $("body").append(html) } }) })
CORS须要浏览器和服务器同时支持。目前,全部浏览器都支持该功能,IE浏览器不能低于IE10。json
整个CORS通讯过程,都是浏览器自动完成,不须要用户参与。对于开发者来讲,CORS通讯与同源的AJAX通讯没有差异,代码彻底同样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感受。跨域
所以,实现CORS通讯的关键是服务器。只要服务器实现了CORS接口,就能够跨源通讯。浏览器
============127.0.0.1:8001=====
$(".get_service").click(function () {
$.ajax({
url:"http://127.0.0.1:8008/service/",
success:function (data) {
console.log(data)
}
})
})
==============127.0.0.1:8002======
def service(request):
info = {"k1":"v1","k2":"v2"}
responce = HttpResponce(json.dumps(info))
responce["Access-Control-Allow-Origin"] = "http://127.0.0.1:8001"
responce["Access-Control-Allow-Origin"] = "*" #表示全部访问经过
return responce