目錄ajax
因爲瀏覽器具備「同源策略」的限制。 若是在同一個域下發送ajax請求,瀏覽器的同源策略不會阻止。 若是在不一樣域下發送ajax,瀏覽器的同源策略會阻止。
CORS,跨站資源共享,本質:設置響應頭。 from django.shortcuts import render,HttpResponse def json(request): response = HttpResponse("JSONasdfasdf") response['Access-Control-Allow-Origin'] = "*" return response
在跨域時,發送的請求會分爲兩種:django
簡單請求,發一次請求。json
設置響應頭就能夠解決 from django.shortcuts import render,HttpResponse def json(request): response = HttpResponse("JSONasdfasdf") response['Access-Control-Allow-Origin'] = "*" return response
複雜請求,發兩次請求。跨域
預檢瀏覽器
請求app
@csrf_exempt def put_json(request): response = HttpResponse("JSON複雜請求") if request.method == 'OPTIONS': # 處理預檢 response['Access-Control-Allow-Origin'] = "*" response['Access-Control-Allow-Methods'] = "PUT" return response elif request.method == "PUT": return response
條件: 一、請求方式:HEAD、GET、POST 二、請求頭信息: Accept Accept-Language Content-Language Last-Event-ID Content-Type 對應的值是如下三個中的任意一個 application/x-www-form-urlencoded multipart/form-data text/plain 注意:同時知足以上兩個條件時,則是簡單請求,不然爲複雜請求