In-depth introduction to jsonp

Source: Internet
Author: User

In-depth introduction to jsonp
Preface

The first time I heard about jsonp, it was actually two years ago. At that time, the lottery module on the activity page had to get a probability from the server. At that time, I didn't understand anything. My colleague said That ajax was used, and my colleague said that dataType was changed to jsonp, I changed it to jsonp. Since the activity page has been completed and jsonp has not been met in the future, during this period, I always thought that jsonp is closely related to ajax and is a special cross-origin form of xhr... it was not until I ran an interview a month ago and asked jsonp if I was abused as a dog that I decided to check jsonp.

Why use jsonp?

I believe that you are familiar with the same origin policy. What have you heard? It doesn't matter. Since it's a simple introduction, let's start from scratch.

If I have written an index page with a request, the request is a json data (I do not know the overview of the json Data's stamp JSON and its usage). I will write down the following code in a simple way:

<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 places both files in the www folder under wamp. The ajax request does not have cross-origin. The perfect result is:

But what if my json file and index file are not in the same domain, that is, cross-origin (for cross-origin users, refer to the same-origin JavaScript Policy?

Try to open an apache port under wamp (for details about how to open it, refer to using multiple ports under WampServer ), put the json file in the service port folder (the landlord sets the port number to 8080 and the default port is port 80) and 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>

Apparently, the cross-origin prompt is displayed! What should I do? Now jsonp is about to crash!

Magic script tag

The script tag is closely related to jsonp, while xhr or ajax in the traditional sense has no relationship with half a cent!

Looking at the corresponding index.html code, we can see that the page references the jquery path of Baidu cdn. We seem to have become accustomed to this method, but after careful consideration, the script tag is completely cross-origin... right. The core of jsonp is to use the cross-origin capability of script tags! As a result, we can dynamically generate a script tag, assign the json url to the src attribute of the script, 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></body>

We created a script tag, and the content of the package in the tag is the json data, but the error is as follows:

The reason is that json data is not a legal js statement. It is the simplest method to put the preceding 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, the. json file does not have to be named like this. changing it to a. js won't be a problem.

The same is true for interaction with the server, such as 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": 10  }';  echo $_GET['callback'].'('.$jsondata.')';?>

It should be noted that the url provided by jsonp (that is, the src of the dynamically generated script tag) will eventually generate a piece of js Code no matter what form it looks like.

JQuery's jsonp Encapsulation

To facilitate development, jq also encapsulates jsonp 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 code above indicates that the callback function name is written to the request file. Because the request is a json file, json is not a server-side Dynamic Language and cannot be parsed. If it is a php or other server-side language, no dead function name is required. For example:

<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": 10  }';  echo $_GET['callback'].'('.$jsondata.')';?>

Of course there are several similar encapsulated methods:

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

Note that the request url of the getJSON method must contain callback = ?, Because no callback function variable is called callback by default during jq encapsulation, the variable value cannot be found in php $ _ GET ['callback.

In general, the callback parameter is not required in the jq Method url. For jsonp in jQuery, the callback parameter is automatically added. By default, the callback parameter in the jsonp request generated by jQuery is like callback = jQuery200023559735575690866_1434954892929. According to the seemingly random name, it corresponds to the processing function of success, so it is generally not needed. 2. If you want to write a dead callback name, refer to the above.

Summary

Due to the restrictions of the same-origin policy, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, Port). To implement cross-origin requests, you can use the script tag to implement cross-origin requests, then, the server outputs JSON data and executes the callback function to solve cross-domain data requests. This is the core of jsonp.

Jsonp principle:

  

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.