Jsonp for cross-domain access

Source: Internet
Author: User
Tags script tag

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:
================================== 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:"", 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:

================================== 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 (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.


With the script tag, cross-domain requests are implemented:

#=============================<button>ajax</button>{% Csrf_token%}<script>function func (name) {alert (name)}</script><script src=""></script>#============================= 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 (" " , 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

 <script> function f () {$.ajax ({URL:   " "   "  jsonp     '  
8001 modified as follows, 8002 unchanged
<script>function f () {$.ajax ({URL:"", 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.