Cross-origin ajax requests

Source: Internet
Author: User

Cross-origin ajax requests
Same-origin policy

The Same origin policy is a convention. It is the core and basic security function of the browser. If the Same origin policy is missing, the normal function of the browser may be affected. It can be said that the Web is built on the basis of the same-origin policy, and the browser is only an implementation of the same-origin policy.

Same-origin policy, a well-known security policy proposed by Netscape. This policy is applicable to all browsers that support JavaScript. The so-called same source means that the domain name, protocol, and port are the same. When Baidu and Google pages are opened on two tab pages of a browser, when the Browser executes a script on the Baidu tab page, it will check which page the script belongs, that is to say, check whether the source and Baidu scripts are the same. If it is not the same source, the browser reports an exception in the console when requesting data, prompting that access is denied.Jsonp

Jsonp is a json cross-domain object. The principle is to bypass the same-origin policy through the cross-origin feature of the script tag.

Think: What's the matter?

1 <script src="http://code.jquery.com/jquery-latest.js"></script>

Use the script tag to implement cross-origin requests. Example:

# =============================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:7766/SendAjax/"></script># =============================http://127.0.0.1:8002/from django.views.decorators.csrf import csrf_exempt@csrf_exemptdef SendAjax(request):    import json    print("++++++++")    # dic={"k1":"v1"}    return HttpResponse("func('www')")  # return HttpResponse("func('%s')"%json.dumps(dic))

This is actually the simple implementation mode of JSONP, or the prototype of JSONP: Create a callback function, call this function on the remote service, and pass the JSON data form as a parameter to complete the callback.

Fill JSON data into the callback function, which is the meaning of JSON + Padding of JSONP.

In general, we hope that the script tag can be dynamically called, rather than being executed without waiting for page display because it is fixed in html. We can dynamically create a script tag through javascript, so that we can flexibly call remote services.

<button onclick="f()">sendAjax</button><script>    function addScriptTag(src){         var script = document.createElement('script');         script.setAttribute("type","text/javascript");         script.src = src;         document.body.appendChild(script);         document.body.removeChild(script);    }    function func(name){        alert("hello"+name)    }    function f(){         addScriptTag("http://127.0.0.1:7766/SendAjax/")    }</script>

To be more flexible, now you can pass the function name of the callback function defined on the client to the server, and the server will return the method with the name of the callback function you defined, pass the obtained json data into this method to complete the callback:

Rewrite f () of 8001:

123 function f(){         addScriptTag("http://127.0.0.1:7766/SendAjax/?callbacks=func")    }

Change views of 8002:

12345678910 def SendAjax(request):     import json     dic={"k1":"v1"}     print("callbacks:",request.GET.get("callbacks"))    callbacks=request.GET.get("callbacks")     return HttpResponse("%s('%s')"%(callbacks,json.dumps(dic)))
JQuery's JSONP implementation getJSON

The jQuery framework also supports JSONP. You can use the $. getJSON (url, [data], [callback]) method.

The html of 8001 is changed:

<button onclick="f()">sendAjax</button><script>    function f(){          $.getJSON("http://127.0.0.1:7766/SendAjax/?callbacks=?",function(arg){            alert("hello"+arg)        });    }    </script>

Views of 8002 are not modified.

The results are the same. Note that a callback parameter must be added after the url so that the getJSON method will know that the service is accessed using JSONP, the question mark after callback is an internal automatically generated callback function name.

What should we do if we want to specify our own callback function name, or if the service specifies a fixed callback function name? We can use the $. ajax method to implement

$. Ajax

The html of 8001 is changed:

<script>    function f(){          $.ajax({                url:"http://127.0.0.1:7766/SendAjax/",                dataType:"jsonp",                jsonp: 'callbacks',                jsonpCallback:"SayHi"           });       }    function SayHi(arg){                alert(arg);            }</script>

Views of 8002 are not modified.

Of course, the simplest form is to use the callback function for processing:

<Script> function f () {$. ajax ({url: "http: // 127.0.0.1: 7766/SendAjax/", dataType: "jsonp", // required, tell the server, this access requires a jsonp result. Jsonp: 'callbacks', // jQuery helps randomly generate: callbacks = "wner" success: function (data) {alert ("hi" + data )}});} </script>

Jsonp: 'callbacks' is the key that defines the callback function. jsonpCallback is the name of the callback function method defined by the frontend: 'sahi ', after the server accepts the corresponding value of the callback key, it can fill in the data and package and return it;

The jsonpCallback parameter can be left unspecified. jquery automatically defines a random name and sends it to the frontend, so the callback function is used to process the corresponding data. Using jQuery, you can easily implement JSONP for cross-origin access.

Note that JSONP must be a GET request.

Jsonp

Jsonp is a json cross-domain object. The principle is to bypass the same-origin policy through the cross-origin feature of the script tag.

Think: What's the matter?

1 <script src="http://code.jquery.com/jquery-latest.js"></script>

Use the script tag to implement cross-origin requests. Example:

# =============================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:7766/SendAjax/"></script># =============================http://127.0.0.1:8002/from django.views.decorators.csrf import csrf_exempt@csrf_exemptdef SendAjax(request):    import json    print("++++++++")    # dic={"k1":"v1"}    return HttpResponse("func('yuan')")  # return HttpResponse("func('%s')"%json.dumps(dic))

This is actually the simple implementation mode of JSONP, or the prototype of JSONP: Create a callback function, call this function on the remote service, and pass the JSON data form as a parameter to complete the callback.

Fill JSON data into the callback function, which is the meaning of JSON + Padding of JSONP.

In general, we hope that the script tag can be dynamically called, rather than being executed without waiting for page display because it is fixed in html. We can dynamically create a script tag through javascript, so that we can flexibly call remote services.

<button onclick="f()">sendAjax</button><script>    function addScriptTag(src){         var script = document.createElement('script');         script.setAttribute("type","text/javascript");         script.src = src;         document.body.appendChild(script);         document.body.removeChild(script);    }    function func(name){        alert("hello"+name)    }    function f(){         addScriptTag("http://127.0.0.1:7766/SendAjax/")    }</script>

To be more flexible, now you can pass the function name of the callback function defined on the client to the server, and the server will return the method with the name of the callback function you defined, pass the obtained json data into this method to complete the callback:

Rewrite f () of 8001:

123 function f(){         addScriptTag("http://127.0.0.1:7766/SendAjax/?callbacks=func")    }

Change views of 8002:

12345678910 def SendAjax(request):     import json     dic={"k1":"v1"}     print("callbacks:",request.GET.get("callbacks"))    callbacks=request.GET.get("callbacks")     return HttpResponse("%s('%s')"%(callbacks,json.dumps(dic)))

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.