JSONP keyword details and json and JSONP differences, Ajax and JSONP differences _javascript skills

Source: Internet
Author: User
Tags script tag

Objective

The first time I heard of JSONP, in fact, 2 years ago. At that time to do an active page of the lottery module, to get a probability from the server, at that time did not understand what, colleagues said with Ajax, I used Ajax, colleagues said DataType changed into JSONP, I changed to JSONP. So the activity page is done, and never met Jsonp, during which I always thought Jsonp and Ajax are closely related, is xhr a special cross-domain form ... Until one months ago an interview, asked Jsonp I was abused as a dog, just decided to see the JSONP, well, the original JSONP is not difficult.

Why do you use JSONP?

I believe you are not unfamiliar with the Cross-domain, the same homology strategy is familiar. What, you've never heard of it? It doesn't matter, since it is simple and simple, then start from the beginning.

If I write the index page with a request that asks for a JSON data (not knowing the hard-poke JSON profile of the JSON data and the usage rollup), simply think about writing 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

The landlord put two files in the Wamp under the WWW folder, the AJAX request did not cross the domain, the perfect results:

But what if my JSON file and the index file are not in one domain, that is, Cross-domain (without the Cross-domain reference JavaScript's homology policy)?

Try to open a new Apache port under the Wamp (don't know how to open the Wampserver under the reference to use multiport access), put the JSON file into the Service port folder (the 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);
 }
 })

Obviously, the hint is cross-domain! What the hell? Then JSONP will be on the horse!

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 jquery path, for such a way we seem to have become accustomed to, but carefully think, the script tag is completely cross-domain ah ... Yes, JSONP's implementation is the core of the use of the ability to cross domain script tags! So we brainwave, it seems we can do this, dynamically generate a script tag, assign the JSON URL to the script src attribute, and then insert 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>

We created a script tag, and the contents of the tag contained exactly the JSON data that was needed, but the error was as follows:

Because JSON data is not a valid JS statement, putting the JSON data above in a callback function is the easiest way:

<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 like this, change to A.js also won't have a little problem.

And if it's the same as interacting with the server, 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 ':
 }';
 Echo $_get[' callback ']. ' ('. $jsondata. ') ';

Note that the URL that Jsonp provides (that is, the src of the dynamically generated script tag), regardless of the form it appears to be, the final generation returns a JS code.

jquery's encapsulation of JSONP

For ease of development, JQ also encapsulates JSONP, encapsulated in Ajax methods.

<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 callback function name that was written in the request file. Because the request is a JSON file, JSON is not a server-side dynamic language can not be resolved, if it is PHP or other server-side language, you do not have to write dead function names, 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 ':
 ';
 Echo $_get[' callback ']. ' ('. $jsondata. ') ';

Of course, there are several other ways of encapsulating the same:

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);

Note that the request address URL for the Getjson method needs to be callback=, because JQ does not encapsulate the method with the default callback function variable named callback, so $_get[' callback ' in PHP cannot find the variable value.

The general JQ method URL does not specify the callback parameter. For JSONP in JQuery, the callback parameter is automatically added. 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 the success That processing function, so generally do not have to specially deal with. If you want to write dead callback name, you can refer to the above.

Summarize

Due to the restriction of the homology policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), and in order to implement Cross-domain requests, a Cross-domain request can be implemented through the script tag, and then the JSON data and the callback function are executed on the server, thus resolving cross-domain data requests. This is the core of JSONP.

  Jsonp principle:

1. First registers a callback on the client, then passes the callback the name to the server.
2. Server sir into 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 into function directly in the form of a parameter, which generates a document of JS syntax and returns it to the client.
3. Client browser, parsing the script tag and executing the returned JavaScript document, at which point the data is passed into the client's predefined callback function as a parameter. (Dynamic execution of callback functions)

The difference between JSON and JSONP, Ajax and JSONP

Although JSON and JSONP differ only by one letter, they are not related.

JSON is a lightweight data interchange format.

JSONP is a Cross-domain data interchange protocol.

The advantages of JSON: (1) It is extremely simple to communicate based on plain text, (2) Lightweight data format for Internet delivery, (3) easy to write and parse.

The difference between Ajax and JSONP:

Same point: All Request a URL

Different points: The core of Ajax is to get content through XMLHttpRequest

The core of JSONP is to dynamically add <script> tag to invoke the JS script provided by the server.

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.