跨域:由於瀏覽器的同源策略,在你請求返回的時候會進行攔截 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