Differences between JSON & JSONP

Keywords: JSON Javascript JQuery xml

When it comes to JSON and JSONP, many people will think that they are related at first. However, although JSON and JSONP have only one letter difference, they are not the same thing at all. This reminds me of a sentence, "The difference between JSON and JSONP is the difference between Lei Feng and Lei Feng Tower". So what is the difference between Lei Feng and Lei Feng Tower?Of course there is no difference!!!

What is JSON

In short, JSON is a text-based data exchange method, or data description format.
Advantages of JSON:
1. Cross-platform delivery is extremely simple based on plain text;
2. Javascript is natively supported, with almost all background languages supported.
3. Lightweight data format, which takes up very few characters, is especially suitable for Internet transmission;
4. Readable, although not as straightforward as XML, but easily recognizable after a reasonable sequential indentation;
5. Easy to write and analyze if you know the data structure;
JSON format:
1. JSON has only two data type descriptors, curly brackets {} and square brackets []. The remaining English colons are: mappers, English commas, separators, and English double quotes.
2. Braces {} are used to describe a set of "different types of set of disordered key-value pairs" and brackets [] are used to describe a set of "same type of ordered data sets".
3. If there are more than one subitem in the above two sets, they are separated by an English comma.
4. Keyvalue pairs should be separated by colons in English and double quotation marks are recommended for key names to facilitate parsing in different languages.
5. Common data types inside JSON are string, number, Boolean, date, null, etc. Strings must be caused by double quotation marks, the rest are not needed.
JSON instance:

// Describe a meeting

var conference = {
    "Conference": "Future Marketing",
    "Date": "2017-6-1",
    "Address": "Beijing",
    "Members": 
    [
        {
            "Name": "Bob",
            "Age": 32,
            "Company": "IBM",
            "Engineer": true
        },
        {
            "Name": "John",
            "Age": 20,
            "Company": "Oracle",
            "Engineer": false
        },
        {
            "Name": "Henry",
            "Age": 45,
            "Company": "Microsoft",
            "Engineer": false
        }
    ]
}

// Read if attendee Henry is an engineer

var henryIsAnEngineer = conference.Members[2].Engineer; 

What is JSONP?

Generation of JSONP
1. A well-known problem is that Ajax requests ordinary files directly without permission across domains. Regardless of whether you are a static page, a dynamic web page, a web service, or a WCF, it is not allowed as long as it is a cross-domain request.
2. However, we also found that js files are invoked on Web pages without cross-domain effects (in addition, we found that all tags with the attribute "src" have cross-domain capabilities, such as

alert('I am a remote file');

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

<!DOCTYPE html>
<html>
<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.
2. Now we define a function on the jsonp.html page and call it from the remote.js.

<!DOCTYPE html>
<html>
<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"});

Viewing the results, the page successfully pops up a prompt window that shows 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?
3. As long as the js script provided by the server is dynamically generated, the caller can pass a parameter to tell the server in the past that "I want a js code that calls XXX function, please return it to me, so the server can generate the js script and respond to the client's requirements.
Look at the code for the jsonp.html page:

<!DOCTYPE html>
<html>
<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 implements a dynamic query, which is also the core part of the jsonp client implementation. We see a code parameter passed in the url called telling the server that I am 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 result into this function to make a call.

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!
4. Give jQuery another piece of code that uses jsonp (we'll still follow the example of the flight information query above, assuming that the jsonp results are the same):

<!DOCTYPE html>
 <html>
 <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>

Similarities and differences between 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 add dynamically

Posted by xxtobirichter on Sun, 23 Jun 2019 10:57:00 -0700