Talk about JSON and JSONP, cross-domain requests

Keywords: JSON JQuery Javascript xml

When it comes to AJAX, there are two unavoidable questions. The first one is in what format does AJAX exchange data? Second, how can cross-domain requirements be addressed? At present, there are different solutions to these two problems, such as data can be described by custom strings or XML, and cross-domain can be solved by server-side proxy.

But the most popular or preferred solution so far is to use JSON to transmit data and JSONP to cross-domain. And that's what this article will tell you.

JSON(JavaScript Object Notation) and JSONP(JSON with Padding) have only one letter difference, but they are not the same thing at all: JSON is a data exchange format, and JSONP is an unofficial cross-domain data interaction protocol created by the wisdom of developers. Let's take the recent popular spy film as an example. JSON is the "code" used by underground party members to write and exchange information, while JSONP is the way of connecting the information written in the code to their comrades. See? One is the format of describing information, and the other is the method agreed by both sides of information transmission.

Now that we talk casually, instead of using dogmatic methods, we focus on helping developers understand whether or not they should choose to use it and how to use it.

What is JSON

As I said earlier, JSON is a text-based data exchange method, or data description format. Whether you should choose JSON or not, you must first pay attention to its advantages.

Advantages of JSON:

1. Based on plain text, cross-platform transmission is extremely simple.

2. Javascript native support, background language almost all support;

3. Lightweight data format, which occupies very few characters, is especially suitable for Internet transmission.

4. It is readable, though not as clear as XML, but it is easy to recognize after reasonable indentation.

5. Easy to write and analyze, of course, if you know the data structure;

The shortcomings of JSON, of course, also exist, but in the author's opinion, they are really insignificant, so they will not be explained separately.

JSON format or rules:

JSON can describe data structure in a very simple way, and XML can do it all, so there is no difference between the two in cross-platform.

1. JSON has only two data type descriptors, brackets {} and square brackets []. The rest of the English colons are mappers, commas, separators and double quotes.

2. Brackets {} are used to describe a set of "different types of disordered key-value pairs" (each key-value pair can be understood as the attribute description of OOP), and brackets [] are used to describe a set of "ordered data sets of the same type" (arrays corresponding to OOP).

3. If there are more than one subitem in the above two sets, they are separated by English commas.

4. Keyvalue pairs should be separated by colons in English and double quotation marks in English are suggested to be added to keynames in order to facilitate the parsing of different languages.

5. The commonly used data types in JSON are string, number, Boolean, date and null. Strings must be caused by double quotation marks. Others are not needed. Date types are special. This is not to be discussed here. It is only suggested that if the client does not need the function of sorting by date, date and time should be passed directly as a string. It can save a lot of trouble.

  JSONExample:

// Describe a person 
var person = {
    "Name": "Bob",
    "Age": 32,
    "Company": "IBM",
    "Engineer": true
}

// Get information about this person 
var personAge = person.Age;

// Describe several people 
var 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 John's company name 
var johnsCompany = members[1].Company;

// Describe a meeting 
var conference = {
    "Conference": "Future Marketing",
    "Date": "2012-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 participant Henry whether he is an engineer or not
var henryIsAnEngineer = conference.Members[2].Engineer;
For JSON, that's all. For more details, please refer to the development process for further study.

What is JSONP

First, how did JSONP come into being?

In fact, there are many online explanations about JSONP, but they are uniform, and in the clouds and mists, it is difficult for many people who have just come into contact to understand it.

1. A well-known problem is that Ajax requests ordinary files directly without permission across domains, regardless of whether you are static pages, dynamic pages, web services, WCF, as long as it is cross-domain requests, it is not allowed;

2. However, we also found that invoking js files on Web pages is not affected by whether they are cross-domain or not. (Besides, we also found that tags with the attribute of "src" have cross-domain capabilities, such as

<!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>
  There is no doubt that the page will pop up a prompt form that shows the success of the cross-domain call.

  2,Now we are jsonp.html Page defines a function, and then remotely remote.js Input data is invoked.

  jsonp.html The 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 are as follows:' + 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 the data brought by remote js"});
After running, the page successfully pops up a prompt window to show that the local function was successfully invoked by cross-domain remote js, and the data brought by remote JS was also received. I'm glad that the goal of remote data acquisition across domains has basically been achieved, but another problem arises. How can I let remote JS know the name of the local function it should call? After all, jsonp servers have to face a lot of service objects, and these service objects have different local functions? Let's look down.

3. Smart developers can easily imagine that as long as the js script provided by the server is dynamically generated, so the caller can pass a parameter to the server and tell it, "I want a js code that calls XXX function, please return to me", so the server can generate the js script and respond to the client's needs.

Look at the code on 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 obtaining flight information query results
    var flightHandler = function(data){
        alert('The result of your inquiry is: fare ' + data.price + ' Yuan,' + 'Surplus ticket ' + data.tickets + ' Zhang.');
    };
    // url addresses that provide jsonp services (regardless of the type of address, 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 begins
    document.getElementsByTagName('head')[0].appendChild(script);
    </script>
</head>
<body>

</body>
</html>

This time, the code has changed a lot, instead of writing the remote js file to death directly, it is encoding to realize dynamic query, which is also the core part of jsonp client implementation, and the focus of this example is how to complete the whole process of jsonp call.

We see that a code parameter is passed in the url of the call, telling the server that I want to check the information of flight CA1998, while the callback parameter tells the server that my local callback function is called flightHandler, so please pass the query results into this function for invocation.

OK, the server is smart. This page called flightResult.aspx generates a piece of code that is provided to jsonp.html.

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

We see that the flightHandler function is passed to a json, which describes the basic information about flights. Run the page and pop up the prompt window successfully. The whole process of jsonp execution is completed smoothly.

4. So far, I believe you can understand the client implementation principle of jsonp, right? What's left is how to encapsulate the code so that it can interact with the user interface to make multiple and repeated calls.

What? You're using jQuery. Want to know how jQuery implements jsonp calls? Okay, so I'll do my best and give you a piece of jQuery code that uses jsonp (we still use the example of the flight information query above, assuming that the result of returning jsonp remains unchanged):

<!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 obtain the jsonp callback function name (generally default: 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 can inquire about flight information: fare: ' + json.price + ' Yuan, balance ticket: ' + json.tickets + ' Zhang.');
             },
             error: function(){
                 alert('fail');
             }
         });
     });
     </script>
     </head>
  <body>
  </body>
 </html>

Isn't it a little strange? Why didn't I write flightHandler this time? And it worked successfully! Ha ha, this is the credit of jQuery. When jQuery is dealing with jsonp type ajax, it still can not help but Tucao, although jQuery also put jsonp in ajax, but they are really not the same thing. It is very cool for you to generate callback function automatically and extract data out for success attribute method.

1. The two technologies of Ajax and jsonp "look" very similar in the way of invocation, and the same purpose is to request a url, and then process the data returned by the server. Therefore, 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-homepage content through XmlHttpRequest, while the core of jsonp is dynamic addition.

Posted by ercantan on Mon, 01 Apr 2019 05:06:29 -0700