"Turn" Jsonp detailed

Source: Internet
Author: User
Tags script tag what callback

Original address: http://www.cnblogs.com/yuzhongwusan/archive/2012/12/11/2812849.html

JSON believes that we all use more, Jsonp I have never had the opportunity to use, but also often see, only know is "used to cross-domain", has not known exactly what is a thing. I finally got it today. The next step is to figure out what JSONP is.

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. It doesn't seem to know what the meaning is, practice it and know it.

Homologous strategy: protocol, domain name, port all the same is called homology.

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 (data) {        console.log (data)    } )    $.get (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:

<srctype= "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.

<typesrc= "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 (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 ({        ' Http://localhost:2701/home/somejsonp '),        "Jsonp",        "callback",        function (data) {Console.log (data)})})     

The results are similar to the above.

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"})

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

ADD Native JS:

<button id= "btn" >click</button><script type= "Text/javascript" >function$ (str) {returndocument.getElementById (str)}functionCreatescript (src) {varScrip=document.createelement (' script '); SCRIP.SRC=src;    Document.body.appendChild (Scrip); }    functionJsonpcallback (JSON) {console.log (JSON);//Object {email= "China", email2= "China 222"}    }    $(' btn '). onclick=function() {Createscript ("Http://localhost:51335/somejson?callback=jsonpcallback")        }</script>

"Turn" Jsonp detailed

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.