跨域:因为浏览器的同源策略,在你请求返回的时候会进行拦截
jsonp 只能发 get 请求
cors 可以发任何请求 ,在响应时加个响应头就行
同源策略对ajax阻拦
同源策略对src或href属性的不阻拦 ajax的本质:
xhr = new XMLHttpRequest();
xhr.open...
xhr.send(...) 解决方案:
- JSONP :原理 面试必问
点击按钮:
动态添加一个
<script src='http://www.baidu.com/users/'></script>
<script>
function func(arg){
alert(arg)
}
</script>
获取数据之后要删除 script标签
<script src='http://www.baidu.com/users/'></script> - CORS - 加响应头 简单与复杂请求的区分:http://www.cnblogs.com/wupeiqi/p/5703697.html a. 简单请求 A网站:
<input type="button" value="获取用户数据" onclick="getUsers()"> <script src="jquery-1.12.4.min.js"></script>
<script>
function getUsers() {
$.ajax({
url: 'http://127.0.0.1:8000/users/',
type:'GET',
success:function (ret) {
console.log(ret)
}
})
}
</script> 服务商:
class UsersView(views.APIView):
def get(self,request,*args,**kwargs): ret = {
'code':1000,
'data':'老男孩'
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response b. 复杂请求(性能上的损耗,options预检,真实的请求,所以要尽量避免发送复杂的请求)
A网站:
<input type="button" value="获取用户数据" onclick="getUsers()"> <script src="jquery-1.12.4.min.js"></script>
<script>
function getUsers() {
$.ajax({
url: 'http://127.0.0.1:8000/users/',
type:'POST',
data: {'k1':'v1'},
headers:{
'h1':'asdfasdfasdf'
},
success:function (ret) {
console.log(ret)
}
})
}
</script> 服务商: class UsersView(views.APIView):
def get(self,request,*args,**kwargs): ret = {
'code':1000,
'data':'老男孩'
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response def post(self,request,*args,**kwargs):
print(request.POST)
ret = {
'code':1000,
'data':'老男孩'
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response def options(self, request, *args, **kwargs):
# self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")
# self.set_header('Access-Control-Allow-Headers', "k1,k2")
# self.set_header('Access-Control-Allow-Methods', "PUT,DELETE")
# self.set_header('Access-Control-Max-Age', 10) response = HttpResponse()
response['Access-Control-Allow-Origin'] = '*' #允许的跨域名
response['Access-Control-Allow-Headers'] = 'h1' #允许的请求头
# response['Access-Control-Allow-Methods'] = 'PUT' #允许的请求方法
return response