In layman Jsonp

Source: Internet
Author: User
Tags script tag

Objective

The first time I heard of Jsonp, actually 2 years ago. At that time in doing an activity page of the lottery module, to get a probability from the server, then what do not understand, colleagues said with Ajax, I use Ajax, colleagues said DataType changed into JSONP, I changed to JSONP. So the activity page finished, and never met Jsonp, in this period I always thought Jsonp with Ajax is closely related, is xhr a special cross-domain form ... Until one months ago an interview, asked Jsonp I was abused into a dog, only decided to see JSONP, well, the original JSONP is not very difficult.

Why do you use JSONP?

I believe that we are not unfamiliar with cross-domain, and also familiar with the same-origin strategy. What, you never heard of it? Never mind, since it is in layman's words, start from the beginning.

If I write an index page, there is a request in the page, the request is a JSON data (do not know the JSON data of the Poke JSON introduction and Usage summary), simple thinking write down the following code:

<script src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script><script type= "text/ JavaScript ">  $.ajax ({    URL: ' Http://localhost/a.json ',    dataType:" JSON ",    success:function (data ) {      console.log (data);    }  }) </script>
{  "name": "Hanzichi",  "age": 10}

Landlord put two files in the Wamp under the WWW folder, Ajax requests do not cross-domain, perfect results:

But what if my JSON file and the index file are not in a single domain, that is, cross-domain (the same origin policy that does not understand cross-domain reference JavaScript)?

Try to open a new Apache port under the Wamp (do not know how to open the reference wampserver with multi-port access), put the JSON file into the Service port folder (landlord set the port number is 8080, the default is 80 port), try to send the request:

<script src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script><script type= "text/ JavaScript ">  $.ajax ({    URL: ' Http://localhost:8080/a.json ',    dataType:" JSON ",    success:function (data) {      console.log (data);    }  }) </script>

Obviously, the hint crosses the domain! What the hell? Then JSONP is going to be the man!

The Magic Script tag

And JSONP is closely related to the script tag, and xhr or the traditional sense of Ajax and it does not have a half-dime relationship!

Then look at the above index.html code, we see the page quoted Baidu CDN's jquery path, for such a way we seem to have become accustomed to, but carefully think, script tag is completely cross-domain ah ... Yes, the core of JSONP's implementation is the cross-domain capability of using the script tag! So we brainwave, it seems we can do this, dynamically generate a script tag, the JSON URL is assigned to the script src attribute, and then the script tag into the DOM ...

<body>  <script src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script>  < Script type= "Text/javascript" >    var s = document.createelement (' script ');    S.SRC = ' Http://localhost:8080/a.json ';    Document.body.appendChild (s);  </script></body>

We created a script tag, and the content inside the tag was the JSON data needed, but the error was as follows:

The reason is because the JSON data is not a valid JS statement, it is the simplest way to put the above JSON data in a callback function:

<body>  <script src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script>  < Script type= "Text/javascript" >    function Jsonpcallback (JSON) {      console.log (JSON);    }    var s = document.createelement (' script ');    S.SRC = ' Http://localhost:8080/a.json ';    Document.body.appendChild (s);  </script></body>
Jsonpcallback ({  "name": "Hanzichi",  "age": 10});

Of course, at this time the A.json file does not have to be named, change to A.js will not have a problem.

And if it's the same with server-side interaction, like PHP:

<body>  <script src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script>  < Script type= "Text/javascript" >    function Jsonpcallback (JSON) {      console.log (JSON);    }    var s = document.createelement (' script ');    S.src= "Http://localhost:8080/test.php?callback=jsonpcallback";    Document.body.appendChild (s);  </script></body>
<?php  $jsondata = ' {'    name ': ' Hanzichi ',    ' age ': ten  } ';  Echo $_get[' callback ']. ' ('. $jsondata. ') ';? >

Note that the URL provided by JSONP (that is, the src of the dynamically generated script tag), regardless of what it looks like, will eventually return a section of JS code.

jquery's Package for JSONP

For ease of development, JQ has also encapsulated the JSONP in the AJAX approach.

<script src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script><script type= "text/ JavaScript ">  $.ajax ({    URL: ' Http://localhost:8080/a.json ',    dataType: ' Jsonp ',    jsonpcallback: ' CallBack ',    success:function (data) {      console.log (data);    }  }); </script>
CallBack ({  "name": "Hanzichi",  "age": 10});

The above code is for the case where the callback function name is written in the request file. Because the JSON file is requested, JSON is not a server-side dynamic language can not be parsed, if it is PHP or other server-side language, you do not have to write dead function name, such as the following:

<script src= ' http://libs.baidu.com/jquery/2.0.0/jquery.min.js ' ></script><script type= "text/ JavaScript ">  $.ajax ({    URL: ' http://localhost:8080/test.php ',    dataType: ' Jsonp ',    success: function (data) {      console.log (data);    }  }); </script>
<?php  $jsondata = ' {'    name ': ' Hanzichi ',    ' age ': ten  } ';  Echo $_get[' callback ']. ' ('. $jsondata. ') ';? >

Of course, there are several ways to encapsulate the same kind of good:

1$.getjson ("http://localhost:8080/test.php?callback=", function (data) {    console.log (data);}); /2$.get (' http://localhost:8080/test.php ', function (data) {    console.log (data);}, ' Jsonp ');  

It is important to note that the request address URL of the Getjson method needs to be taken with callback=, since JQ does not have a default callback function variable named callback when it encapsulates the method, so $_get[' callback ' in PHP cannot find the variable value.

The callback parameter is not specified in the generic JQ method URL. For JSONP in JQuery, the callback parameter is added automatically. By default, the callback parameter in the JSONP request generated by JQuery is shaped like callback=jquery200023559735575690866_1434954892929, which is based on seemingly random names, corresponding to success That handler function, so you don't have to deal with it intentionally. Second, if you want to write dead callback name, you can refer to the above.

Summarize

Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), in order to implement cross-domain requests, cross-domain requests can be implemented through the script tag, and then output JSON data on the server and execute callback functions to resolve cross-domain data requests. This is the core of JSONP.

Jsonp principle:

    1. First register a callback with the client and then pass the callback name to the server.
    2. The server becomes JSON data. Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up. Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.
    3. The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function)

Http://www.cnblogs.com/zichi/p/4593047.html

In layman Jsonp

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.