Ajax Jsonp Cross-domain request implementation methods _ajax related

Source: Internet
Author: User
Tags script tag

What is cross domain?

Simply put, for security reasons, JavaScript on the page cannot access data on other servers, or "homology policies." Cross-domain is through some means to circumvent the same-origin policy restrictions, to achieve the effect of communication between different servers.

Specific policy restrictions can be seen in the following table:

Url Description Allow communication
Http://www.a.com/a.js
Http://www.a.com/b.js
Under the same domain name Allow
Http://www.a.com/lab/a.js
Http://www.a.com/script/b.js
Different folders under the same domain name Allow
Http://www.a.com:8000/a.js
Http://www.a.com/b.js
Same domain, different port Not allowed
Http://www.a.com/a.js
Https://www.a.com/b.js
Same domain, different protocol Not allowed
Http://www.a.com/a.js
Http://127.0.0.100/b.js
Domain name and domain name corresponding IP Not allowed
Http://www.a.com/a.js
Http://script.a.com/b.js
Primary domain is the same, subdomain is different Not allowed
Http://www.a.com/a.js
Http://a.com/b.js
Same domain name, different level two domain name (IBID.) Not allowed
Http://www.a.com/a.js
Http://www.b.com/b.js
Different domain names Not allowed

What is JSONP?

JSON (JavaScript Object notation) is a lightweight data interchange format, while JSONP (JSON with Padding) is a "usage pattern" of JSON, which enables Cross-domain acquisition of data.

Jsonp principle of cross-domain

Under the same-source policy, a page under a server cannot obtain data other than the server, but the IMG, IFRAME, script, and so on are the exceptions, and these tags can be requested from the SRC attribute to data on other servers. With the open strategy of the script tag, we can implement Cross-domain request data, and of course, we need the cooperation of the service side. When we normally request a JSON data, the server returns a string of JSON-type data, and when we use the JSONP pattern to request data, the server returns an executable JavaScript code.

cross-domain: js has a homology limit, simply say the source is not the same words can not interact with each other. Then how to calculate the source is not the same, for example: Browser access--> Server A---> get page A---page A of the JS script can only access the resources of Server A ( The same domain name and port, in addition to the domain name and the corresponding IP is not homologous, or both domain names, or both IP.

The above is JS Cross-domain problem, but here need to pay attention to is that server A is not cross-domain problem, this only JS exists this problem, that is to say: Page a js--> server a---> Cross-domain resources, this path is OK. Only JS---in Page a > Cross-domain resources, this path is not possible.

And then say the JSONP in the solution, which is not a format, but a solution.

JSONP principle: JS Although there are homologous restrictions, but the introduction of JS file when there is no such restrictions, that is to say:

<script type= "Text/javascript" src= "Xxx/xxxx.js" ></script>

When the SRC attribute is introduced into JS file, there is no homologous restriction, at this time, the extraterritorial resources can be introduced. The principle of JSONP is here, by dynamically creating more than one line of JS to introduce the statement, Access to extraterritorial resources through its SRC attribute. And the extraterritorial resource server returns a string that can be resolved as a JS statement to achieve the purpose of returning the result, in the form of:

 
 

The callback is the name that needs to be agreed in advance, the green Word part is to return to the JSON string, and then stitching into the above form to return directly. Such a page in the JS from the server received this stitching string, will directly execute the local name of the callback JS method, This is why callback this requires prior agreement, the need to ensure that the page side of this JS method, this method passed the parameter is the server side of the return value.

Ajax is a support JSONP, so all the trouble things will be done for us, as follows:

$.ajax ({
     type: ' Get ',
     URL: "http://127.0.0.1:8080/xxx/xxx",
     Async:false,
     dataType: "Jsonp"
     , JSONP: "Callback",
     success:function (result) {
       ...
     },
     timeout:3000 
  });

The Scarlet Letter section identifies the way we call it using JSONP, which is actually not the traditional Ajax get request at this point, and it's really implemented in the way we said above. Where the red-letter part of the callback for us to communicate with the server side, This request is sent to the server side, which is actually like this:

Http://127.0.0.1:8080/xxx/xxx?callback=jqueryxxxx

The server side needs to take the value by callback (similar to Request.getparameter ("callback"), which is to take the automatically generated values such as the back jqueryxxxx, This value is actually the corresponding success callback method in the Ajax method that we are sending the request, and if the server side returns

Jqueryxxxx ({"ret": "OK"})

The success method is automatically executed in the page and the {ret: OK} is passed to the parameter result of the success method.

This is the process by which Ajax implements Cross-domain access through JSONP. You can see that basically we do not need to do any additional operations, all packaged.

PS: How to use JSONP to get data across domains in jquery

The first approach is to set datatype as ' Jsonp ' in an AJAX function:

$.ajax ({
    dataType: ' Jsonp ',
    URL: ' http://www.a.com/user?id=123 ',
    success:function (data) {
        / Process data
    }
});

The second approach is to use Getjson to implement, just add callback= to the address of the parameter can be:

$.getjson (' http://www.a.com/user?id=123&callback=? ', function (data) {
    //process information
});

You can also simply use the Getscript method:

In this case, you can also define the Foo method
function foo (data) {
    //process data
}
$.getjson (' http://www.a.com/user?id=123 &callback=foo ');

The application of JSONP

Jsonp can play a very important role in the Open API, open APIs are used on developers ' own applications, and many applications are often on the developer's server rather than on Sina Weibo's servers, so cross-domain request data is a big problem for developers to solve, The broad open platform should achieve the support of JSONP, this Sina Weibo open platform will do very well (although some APIs are not stated, but in fact can be invoked using JSONP).

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.