Using JSONP to implement cross-domain requests

Source: Internet
Author: User
Tags script tag what callback

A passage from Baidu Encyclopedia:

JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to address cross-domain data access issues in mainstream browsers. because of the same-origin policy, Web pages that are generally located in server1.example.com cannot communicate with servers that are not server1.example.com, while HTML <script> elements are an exception. Using this open strategy of <script>, the Web page can get JSON data that is dynamically generated from other sources, and this usage pattern is called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which executes with a JavaScript interpreter instead of parsing with a JSON parser.

From the folk metaphor:

JSON (JavaScript Object Notation) and Jsonp (JSON with Padding) have only one letter difference, but they're not the same thing at all: JSON is a data interchange format, And Jsonp is a kind of unofficial cross-domain data interaction protocol that is created by the ingenuity of the developers. We use the latest spy war film to make an analogy, JSON is used by the underground to write and exchange information "code", and Jsonp is the message written with the signal to his comrades using the connection method. Did you see that? One is the format of describing information, and the other is the method agreed by both parties to the information delivery.

Homologous policy

First, for security reasons, the browser is a mechanism of the same origin policy, which prevents a document or script loaded from one source from getting or setting the properties of another source-loaded document.

1. Build two pages at a random

A port is 2698, a 2701, by definition they are different sources.

2. Use jquery to initiate requests for different sources

On a 2698-port page, add a button to the Click event to randomly initiate two requests to the port 2701 domain.

$ ("#getOtherDomainThings"). Click (function () {    $.get ("Http://localhost:2701/Scripts/jquery-1.4.4.min.js", function (data) {        console.log (data)    })    $.get ("Http://localhost:2701/home/index", function (data) {        Console.log (data)})    })

According to the homologous strategy, it is obviously tragic. The browser will block and will not initiate this request at all. (not allowed by Access-control-allow-origin)

OK, the original JSONP is to solve the problem.

Cross-domain capabilities for script tags

I do not know if you know CDN this thing, such as Microsoft's Cdn, using it, our webpage can not provide jquery, by Microsoft's website to help us provide:

<script src= "Http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type= "Text/javascript" ></script>

Back to our 2698-Port page, above we have a request for a jquery file for the 2701-port domain in the Click event, this time using the script tag to request.

<script type= "Text/javascript" src= "Http://localhost:2701/Scripts/jquery-1.4.4.min.js" ></script>

Of course, 200,ok.

The same Port 2698 Web page initiates a request for a 2701 domain, and the setting of the SCR attribute in the script is OK, and the other way is tragic. Using script's cross-domain capabilities, this is the basis of JSONP.

Using script to get JSON from different sources

Since it's called JSONP, it's clear that the purpose is JSON, and it's cross-domain fetching. According to the above analysis, it is easy to think: Using JS to construct a script tag, the JSON URL is assigned to the SCR property of the script, the script inserted into the DOM, let the browser to get. Practice:

function Createscript (SRC) {    $ ("<script><//script>"). attr ("src", src). AppendTo ("Body")}

Add a button event to test:

$ ("#getOtherDomainJson"). Click (function () {    $.get (' Http://localhost:2701/home/somejson ', function (data) {        console.log (data)})    })

First, the first browser, Http://localhost:2701/home/somejson this URL does exist a JSON, and on the 2698 page with a script tag to request the 2701 this URL is also 200OK, But the bottom of the report JS syntax is wrong. The original script tag after loading, will immediately put the response as JS to execute, it is obvious {"Email": "[email protected]", "Remark": "I come from the Far East"} is not a valid JS statement.

Use script to get exotic JSONP

Obviously, putting the above JSON into a callback method is the simplest way. For example, it becomes this:

If there is jsonpcallback this method, then Jsonpcallback ({"Email": "[email protected]", "Remark": "I come from the Far East"}) is a valid JS statement.

Because the server does not know what the client callback is, it is impossible to hard code into Jsonpcallback, so take a querystring to let the client tell the service side, what callback method, of course, QueryString key to comply with the service side of the contract, The above is the "callback".

To add a callback function:

function Jsonpcallback (JSON) {    console.log (JSON)}

Change the previous method slightly to the parameter:

$ ("#getJsonpByHand"). Click (function () {    createscript ("Http://localhost:2701/home/somejsonp?callback=jsonpcallback")})

200OK, the server returned Jsonpcallback ({"Email": "[email protected]", "Remark": "I come from the Far East"}), we also wrote the Jsonpcallback method, of course, will execute. OK, the JSON was successfully obtained. Yes, this is the whole JSONP.

Using jquery to get JSONP

In this way, the script tag is inserted and a callback is defined, which makes it a little cumbersome to use jquery to directly get the JSON data you want, as well as the JSONP:

$ ("#getJsonpByJquery"). Click (function () {    $.ajax ({        URL: ' Http://localhost:2701/home/somejsonp '),        DataType: "Jsonp",        Jsonp: "Callback",        success:function (data) {            console.log (data)})    })
Attach a service-side code, using the Java language
Response.setcontenttype ("Text/plain;charset=utf-8");        PrintWriter out = null;        try {            out = Response.getwriter ();            String Jsonpdata = callback + "(" + Jsonobject.tojson ("encapsulated JSON data") + ")";            Out.print (Jsonpdata);        } catch (IOException e) {            logger.error ("Response.getwriter () error", e);        } Finally {            if (out! = null) {                out.flush ();                Out.close ();            }        }

Isn't it a little strange? Why didn't I write the callback function? And it worked! Haha, this is the credit of jquery, jquery in the processing of JSONP type of Ajax (or can not help to spit groove, although jquery also put Jsonp into Ajax, but in fact, they really are not a thing), Is it cool to automatically generate callback functions for you and take the data out for the Success property method to invoke?

Summarize

One sentence is to use the script tag to bypass the same-origin policy, get a similar data, Jsonpcallback is the page exists callback method, parameter is the JSON to get.

Jsonpcallback ({"Email": "[email protected]", "Remark": "I come from the Far East"})

1, Ajax and JSONP the two technologies in the invocation of the way "looks" very much like, the purpose is the same, is to request a URL, and then the server to return the data processed, so the jquery and ext and other frameworks have Jsonp as a form of Ajax encapsulation;

2, but Ajax and JSONP are actually different things in nature. The core of Ajax is to obtain non-page content through XMLHttpRequest, while the core of JSONP is dynamic add <script> tag to invoke the JS script provided by the server.

3, so that, in fact, the difference between Ajax and JSONP is not whether cross-domain, AJAX through the service-side proxy can be implemented across domains, JSONP itself does not exclude the same domain data acquisition.

4, there is, Jsonp is a way or non-mandatory protocol, like Ajax, it does not have to use JSON format to pass the data, if you want to, the string is OK, but this is not conducive to the use of JSONP to provide public services.

All in all, JSONP is not a special case of Ajax, even if a giant like jquery encapsulates Jsonp into Ajax, it can't change that!

ADD Native JS:

<button id= "BTN" >click</button>
<script type= "Text/javascript" >
function $ (str) {
return document.getElementById (str)
}
function Createscript (SRC) {
var scrip=document.createelement (' script ');
SCRIP.SRC=SRC;
Document.body.appendChild (Scrip);
}
function Jsonpcallback (JSON) {
Console.log (JSON);//object {email= "China", email2= "China 222"}
}
$ (' btn '). Onclick=function () {
Createscript ("Http://localhost:51335/somejson?callback=jsonpcallback")
}
</script>

Reference Documentation:

Http://www.cnblogs.com/lemontea/archive/2012/12/11/2812268.html

http://kb.cnblogs.com/page/139725/

Using JSONP to implement cross-domain requests

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.