同源策略与Jsonp
同源策略
同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
同源策略,它是由Netscape提出的一个著名的安全策略。现在所有支持JavaScript 的浏览器都会使用这个策略。所谓同源是指,域名,协议,端口相同。当一个浏览器的两个tab页中分别打开来 百度和谷歌的页面当浏览器的百度tab页执行一个脚本的时候会检查这个脚本是属于哪个页面的,即检查是否同源,只有和百度同源的脚本才会被执行。
如果非同源,那么在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。
示例:
项目1:
setting.py
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
静态文件:
<script src="http://code.jquery.com/jquery-latest.js"></script>
urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'index/$',views.index), url(r'ajax_send/$',views.ajax_send), ]
views.py
from django.shortcuts import render,HttpResponse
def index(request):
return render(request,"index.html")
def ajax_send(request):
return HttpResponse("项目1的数据!")
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h3>pro1的首页</h3>
<button class="b1">send a request</button>
</body>
<script src="/static/jquery.js"></script>
<script>
$(".b1").click(function(){
$.ajax({
//url:"/ajax_send", //访问项目1的本路径
url:"http://127.0.0.1:8080/ajax_send", //访问项目2的路径
success:function(data){
alert(data);
}
})
})
</script>
</html>
项目2的代码同上
//===================================setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
//===================================urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'index/$',views.index),
url(r'ajax_send/$',views.ajax_send),
]
//===================================views.py
from django.shortcuts import render,HttpResponse
def index(request):
return render(request,"index.html")
def ajax_send(request):
return HttpResponse("项目2的数据!")
//===================================index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h3>pro2的首页</h3>
<button class="b2">send a request</button>
</body>
<script src="/static/jquery.js"></script>
<script>
$(".b2").click(function(){
$.ajax({
url:"/ajax_send",
success:function(data){
alert(data);
}
})
})
</script>
</html>
同源问题: