A first look at ajax (2) - encapsulating jsonp

Reprinted from
Say JSON and JSONP, maybe you'll be clear-cut

brief introduction

What is jsonp

    JSONP(JSON with Padding) is a "usage mode" of JSON that can be used to solve cross-domain data access problems in mainstream browsers.
    Due to the homology policy, web pages located in server1.example.com in general cannot communicate with servers that are not server1.example.com.
    With this open policy of the <script>element, web pages can get JSON data generated dynamically from other sources, and this usage pattern is called JSONP.
    The data captured with JSONP is not JSON, but any JavaScript that is executed with a JavaScript literal rather than parsed with a JSON parser.

To put it simply

    In order to facilitate the use of data by clients, an informal transport protocol has gradually been formed, which is called JSONP.
    One of the key points of this protocol is to allow the user to pass a callback parameter to the server.
    The callback parameter is then used as the function name to wrap the JSON data when the server returns the data.
    This allows clients to customize their own functions to automatically process the returned data.

The first example of jsonp

The remote.js file code in the root directory of remote server remoteserver.com is as follows:

alert('I am a remote file');

There is a jsonp.html page code under the local server.com as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://remoteserver.com/remote.js"></script>
</head>
<body>

</body>
</html>

Undoubtedly, a prompt form will pop up on the page showing that the cross-domain call was successful.

A second example of jsonp

Now we define a function on the jsonp.html page and call it from remote.js with incoming data.
The jsonp.html page code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
    var localHandler = function(data){
        alert('I am a local function and can be cross-domain remote.js File Call, Remote js The data is:' + data.result);
    };
    </script>
    <script type="text/javascript" src="http://remoteserver.com/remote.js"></script>
</head>
<body>

</body>
</html>

The remote.js file code is as follows:

localHandler({"result":"I am remote js Data brought"});

After running, the page successfully pops up a prompt window showing that the local function was successfully called by a cross-domain remote JS and that it received data from the remote js.I'm glad that the goal of getting data remotely across domains has basically been achieved, but another problem has arisen. How can I tell a remote JS what the name of the local function it should call?After all, jsonp's servers have to face many service objects, and these service objects have different local functions?Let's look down.
Smart developers can easily imagine that as long as the js scripts provided by the server are dynamically generated, the caller can pass a parameter that tells the server in the past "I want a js code that calls XXX functions, please return to me", so the server can generate the js scripts and respond to the client's needs.
  

The third example of jsonp

Look at the code for the jsonp.html page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
    // Callback function after getting flight information query result
    var flightHandler = function(data){
        alert('The result of your flight query is: Ticket Price ' + data.price + ' Yuan,' + 'Balance ' + data.tickets + ' Zhang.');
    };
    // url address that provides the jsonp service (regardless of the address type, the resulting return value is a javascript code)
    var url = "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler";
    // Create script tags and set their properties
    var script = document.createElement('script');
    script.setAttribute('src', url);
    // Add the script tag to the head, and the call starts
    document.getElementsByTagName('head')[0].appendChild(script);
    </script>
</head>
<body>

</body>
</html>

This time, the code changes a lot. Instead of writing the remote js file directly to death, the code implements dynamic query, which is also the core part of jsonp client implementation. The focus in this example is how to complete the whole process of jsonp call.
We see a code parameter passed in the url called telling the server that I'm looking for information about flight CA1998, while the callback parameter tells the server that my local callback function is called flightHandler, so pass the query results into this function to make the call.
OK, the server is smart. This page called flightResult.aspx generates a code like this that is provided to jsonp.html (the implementation on the server is not shown here, it's not about the language you choose, it's about stitching strings after all):
  

flightHandler({
    "code": "CA1998",
    "price": 1780,
    "tickets": 5
});

As we can see, what is passed to the flightHandler function is a json that describes the basic information about a flight.Run the page, pop up the prompt window successfully, and the whole process of jsonp execution is completed successfully!
So far, I'm sure you can understand the client implementation of jsonp?What remains is how to encapsulate the code so that it can interact with the user interface to make multiple and repeated calls.
What?You are using jQuery and want to know how jQuery implements jsonp calls?Okay, so I'll do it all, and give you another piece of jQuery code that uses jsonp (we'll still follow the example of the flight information query above, assuming that the jsonp results are the same):

jquery's jsonp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
 <head>
     <title>Untitled Page</title>
      <script type="text/javascript" src=jquery.min.js"></script>
      <script type="text/javascript">
     jQuery(document).ready(function(){
        $.ajax({
             type: "get",
             async: false,
             url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
             dataType: "jsonp",
             jsonp: "callback",//The parameter name passed to the request handler or page to get the jsonp callback function name (typically, callback)
             jsonpCallback:"flightHandler",//Custom jsonp callback function name, default to jQuery automatically generated random function name, can also write "?", jQuery will automatically process data for you
             success: function(json){
                 alert('You have inquired about the flight information: Ticket price: ' + json.price + ' Yuan, Balance: ' + json.tickets + ' Zhang.');
             },
             error: function(){
                 alert('fail');
             }
         });
     });
     </script>
     </head>
  <body>
  </body>
 </html>

Isn't it a little strange?Why didn't I write the flightHandler function this time?And it worked successfully!Ha-ha, that's what jQuery does. When jQuery deals with Ajax of type jsonp (it still can't help spitting, although jQuery also classifies jsonp as ajax, they really aren't the same). Isn't it nice to automatically generate callback functions for you and take out the data for the success attribute method to call?

ajax and jsonp

1. Both Ajax and jsonp technologies "look" alike in the way they are invoked, as well as in the purpose of requesting a url and then processing the data returned by the server, so jquery and ext frameworks encapsulate jsonp as a form of ajax;
2. But ajax and jsonp are essentially different things.The core of ajax is to get non-page content through XmlHttpRequest, while the core of jsonp is to dynamically add tags <-script> to invoke js scripts provided by the server.
3. So in fact, the difference between ajax and jsonp is not whether or not they are cross-domain. ajax can achieve cross-domain through the service-side proxy, and jsonp itself does not exclude the acquisition of data in the same domain.
4. Also, jsonp is a way or non-mandatory protocol, and like ajax, it does not have to transfer data in json format. Strings do work if you want, but this does not benefit from jsonp providing public services.
  
In a word, jsonp is not a special case of ajax, even if giants like jquery encapsulate jsonp in ajax, it can't change that!

Keywords: JQuery JSON Javascript Attribute

Added by zippee on Mon, 20 May 2019 04:30:30 +0300