Homologous policy
The same Origin policy is a convention that is the most central and basic security feature of the browser, and if the same origin policy is absent, the normal functionality of the browser may be affected. It can be said that the Web is built on the basis of the same origin policy, the browser is only for the same origin of the implementation of the policy.
Homologous strategy, which is a well-known security policy proposed by Netscape. This policy is now used by all JavaScript-enabled browsers. The so-called homology refers to the same domain name, protocol, and port. When a browser's two tab pages are opened to Baidu and Google's page when the browser's Baidu tab page executes a script will check the script belongs to which page, that is, check whether the same origin, only and Baidu homologous script will be executed. In the case of non-homologous, when requesting data, the browser will report an exception in the console prompting for access denied. Example Project A:
==================================http://127.0.0.1: 8001 Index of item<! DOCTYPE html>"en">"UTF-8"> <title>Title</title> <script src="Http://code.jquery.com/jquery-latest.js"></script>{% Csrf_token%}<script> $("Button"). Click (function () {$.ajax ({URL:"http://127.0.0.1:8002/SendAjax/", type:"POST", data:{"username":"Bender","Csrfmiddlewaretoken":$("[name= ' Csrfmiddlewaretoken ']"). Val ()}, Success:function (data) {alert (data)})})</script></body>: 8001 views of the projectdefIndex (Request):returnRender (Request,"index.html")defAjax (Request):ImportJSONPrint(Request. POST)returnHttpResponse (Json.dumps ("Hello"))
Item B:
==================================http://127.0.0.1: 8002 Index of item<! DOCTYPE html>"en">"UTF-8"> <title>Title</title> <script src="Http://code.jquery.com/jquery-latest.js"></script>{% Csrf_token%}<script> $("Button"). Click (function () {$.ajax ({URL:"/sendajax/", type:"POST", data:{"username":"Bender","Csrfmiddlewaretoken":$("[name= ' Csrfmiddlewaretoken ']"). Val ()}, Success:function (data) {alert (data)})})</script></body>: 8002 views of the projectdefIndex (Request):returnRender (Request,"index.html") fromDjango.views.decorators.csrfImportcsrf_exempt@csrf_exemptdefSendajax (Request):ImportJSONreturnHttpResponse (Json.dumps ("Hello2"))
When you click on the button of item 1, the request is sent, but you will find the following error:
Cross-origin requests have been intercepted: the same origin policy prohibits reading remote resources located in http://127.0.0.1:8002/SendAjax/. (Reason: CORS header is missing ' Access-control-allow-origin ').
Note, however, that access to Project 2 has already occurred, indicating that the browser has intercepted the results of non-homologous requests returned.
Jsonp
With the script tag, cross-domain requests are implemented:
#=============================http://127.0.0.1:8001/index<button>ajax</button>{% Csrf_token%}<script>function func (name) {alert (name)}</script><script src="http://127.0.0.1:8002/SendAjax/"></script>#=============================http://127.0.0.1:8002/ fromDjango.views.decorators.csrfImportcsrf_exempt@csrf_exemptdefSendajax (Request):ImportJSONPrint("++++++++") #dic={"K1": "v1"} returnHttpResponse ("func (' Yuan ')")#return HttpResponse ("func ('%s ')"%json.dumps (DIC))
This is actually the simple implementation pattern of JSONP, or the JSONP prototype: Create a callback function and then call the function on the remote service and pass the JSON data as parameters to complete the callback.
Fill in the JSON data into the callback function, which is the meaning of Jsonp's json+padding.
The realization of jquery to Jsonp Getjson
The jquery framework also certainly supports JSONP, which can be used with the $.getjson (Url,[data],[callback]) method
<button onclick="f ()">sendAjax</button><script> function f ( ) { $.getjson ("http://127.0.0.1:8002/SendAjax/?callbacks=? " , function (ARG) { alert ("hello"+Arg) }); </script>
8001 modified as follows, 8002 unchanged
The result is the same, note that after the URL must be added a callback parameter, so that the Getjson method will know is to use JSONP way to access the service, callback the question mark is the internal automatically generated a callback function name.
Also, what if we want to specify our own callback function name, or if the service prescribes a fixed callback function name? We can use the $.ajax method to implement
$.ajax
<script> function f () {$.ajax ({URL: " http://127.0.0.1:7766/sendajax/ " " jsonp '
8001 modified as follows, 8002 unchanged
<script>function f () {$.ajax ({URL:"http://127.0.0.1:8002/SendAjax/", DataType:"Jsonp", //must have, tell the server that this visit is going to be a jsonp result. JSONP:'Callbacks',//jquery help randomly generated: callbacks="Random Character creation"success:function (data) {alert ("Hi"+data)} }); }</script>
callback function Version
JSONP: ' callbacks ' is defined as a key to hold the callback function, Jsonpcallback is the front-end definition of the callback function method name ' Sayhi ', the server side accepts the callback key corresponding value can be filled in the data package returned;
The Jsonpcallback parameter can be undefined, jquery automatically defines a random name, and the front end has to use the callback function to process the corresponding data. jquery makes it easy to implement JSONP for cross-domain access.
Note Jsonp must be a GET request
<input type="Button"onclick="ajaxrequest ()"Value="cross-Domain ajax"/><div id="Container"></div> <script type="Text/javascript">function Ajaxrequest () {$.ajax ({URL:'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403', type:'GET', DataType:'Jsonp', Jsonp:'Callback', Jsonpcallback:'List', Success:function (data) {$.each (data.data,function (i) { VAR item=Data.data[i]; var str="<p>"+ Item.week +"</p>"; $('#container'). append (str); $.each (Item.list,function (j) {var temp="<a href= '"+ Item.list[j].link +"' >"+ Item.list[j].name +"</a><br/>"; $('#container'). Append (temp); }); $('#container'). Append (""); }) } }); }</script>
cross-domain Applications
Jsonp for cross-domain access