1. Generally when we request resources across domains in Ajax, the browser console will report the following error:
Code:
$.ajax ({ URL:"http://127.0.0.1:8000/get_data.html", success: Function (response) { alert (response) }})
Error:
The reason is because, in the response of the cross-domain return value, a header value is missing: Access-control-allow-origin, which causes the browser to intercept .... This is called the browser's homologous policy.
At this point, we offer 2 methods.
Method 1:jsonp
Code
$.ajax ({ "http://127.0.0.1:8000/get_data.html", "get" , "JSONP", "Callback", "list666"}); function list666 (ARG) { alert (ARG)}
Principle:
1. Tags with src attributes, such as img,script,iframe, are not constrained by the same Origin policy
2. The principle of the above-mentioned JSONP code is shown below, that is, by constructing a script tag, the SRC value is assigned to it, and then added to the head, when executed, from the URL to get the data, the data is list666 ("confidential data"), the function is thrown to execute.
function list666 (ARG) { alert (ARG)}function jsonp () { var spt = Document.createelement ("script"); = "http://127.0.0.1:8000/get_data.html?callback=list666" document.head.appendChild (SPT)}jsonp ()
3. The same site that needs to be requested is processed as follows:
def Get_data (Request): = Request. Get.get ("callback") return httpresponse ("%s" (' Confidential data ')" % func_name)
Method 2:cors, i.e. cross-domain resource sharing (cors,cross-origin Resource sharing), essentially sets the response header, allowing the browser to allow cross-domain requests.
Front-end Normal request:
$.ajax ({ "http://127.0.0.1:8000/get_data.html", "Get", success: function (ARG) { alert (ARG) }});
Add the request header information to the backend of the cross-domain:
def Get_data (Request): = HttpResponse (' confidential data ') response[' Access-control-allow-origin'"http://127.0.0.1:8005" return response
The above code can handle a simple request, such as handling complex requests, such as put, custom request headers, which need to be sent 2 times, the first is a preflight, and the preflight will continue to send the request.
The following information needs to be added to the response
response['access-control-allow-origin'"http://127.0.0.1:8888" response['access-control-allow-methods'"PUT " response['access-control-allow-headers'"xxx "
More information: Ajax full set of JavaScript, Dom, and jquery
Ajax cross-domain requests