Talk about JSON and JSONP

foreword

When it comes to AJAX, it will inevitably face two problems. The first is what format does AJAX exchange data in? The second is how to solve cross-domain requirements? These two problems currently have different solutions. For example, data can be described with custom strings or XML, and cross-domain can be solved through server-side proxies.

But so far the most respected or preferred solution is to use JSON to transmit data, and to rely on JSONP to cross domains. And that's what this article is about.

Although JSON and JSONP differ by only one letter, they are not the same thing at all: JSON is a data exchange format , while JSONP is an unofficial cross-domain data interaction created by the ingenuity of developers. agreement . Let's take the recent popular spy war movies as an example. JSON is the "crypto" used by underground parties to write and exchange information, while JSONP is the connection method used to transmit the information written in the code to one's comrades. did you see? One is the format of the description information, and the other is the method agreed upon by both parties of the information transmission.

Now that we're talking casually, let's stop talking dogmatically and focus on helping developers understand if and how to choose to use it.

What is JSON?

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

Advantages of JSON:

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

  2. Javascript native support, almost all background languages ​​are supported;

  3. Lightweight data format, occupying very few characters, especially suitable for Internet transmission;

  4. It is more readable, although it is not as clear as XML, but it is still easy to identify after reasonable indentation;

  5. Easy to write and parse, of course, provided you know the data structure;

There are of course disadvantages of JSON, but in the author's opinion it is really irrelevant, so I will not explain it separately.

JSON format or rules:

JSON can describe data structures in a very simple way, and XML can do it, so in terms of cross-platform, the two are completely comparable.

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

  2. Braces {}are used to describe a set of "unordered sets of key-value pairs of different types" (each key-value pair can be understood as an OOP attribute description), and square brackets are []used to describe a set of "ordered sets of data of the same type" ( Arrays that can correspond to OOP).

  3. If there are multiple sub-items in the above two sets, they are separated by commas ,.

  4. The key-value pair is separated by an English colon :, and it is recommended to add English double quotation marks to the key name ""to facilitate parsing in different languages.

  5. The common data types in JSON are nothing more than strings, numbers, booleans, dates, and nulls. Strings must be enclosed in double quotation marks, and the rest are not used. Date types are special, so I will not describe them here. If the client does not have the function of sorting by date, then it is good to pass the date and time directly as a string, which can save a lot of trouble.

JSON example:

// 描述一个人

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

// 获取这个人的信息

var personAge = person.Age;

// 描述几个人

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
    }
]

// 读取其中John的公司名称

var johnsCompany = members[1].Company;

// 描述一次会议

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
        }
    ]
}

// 读取参会者Henry是否工程师

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

So much to say about JSON, for more details, please refer to the materials for in-depth study during the development process.

What is JSONP?

Let's talk about how JSONP is generated:

In fact, there are many explanations about JSONP on the Internet, but they are all the same, and it is difficult for many people who have just come into contact with them to understand. helpful.

  1. A well-known problem, Ajax directly requests ordinary files, there is a problem of cross-domain unauthorized access, regardless of whether you are a static page, dynamic page, web service, or WCF, as long as it is a cross-domain request, it is not allowed;

  2. However, we also found that when calling js files on a Web page, it is not affected by whether it is cross-domain (not only that, we also found that all "src"tags with this attribute have cross-domain capabilities, such as <script>, <img>, <iframe>);

  3. So it can be judged that at the current stage, if you want to access data across domains through the pure web side (ActiveX controls, server-side proxies, and other methods that belong to the future HTML5are Websocketnot counted), there is only one possibility, and that is to try to load the data into the remote server. js format file for client call and further processing;

  4. It just so happens that we already know that there is a pure character data format called JSON that can describe complex data concisely. What’s even better is that JSON is also natively supported by js, so the data in this format can be processed almost arbitrarily on the client side;

  5. This solution is ready to come out. The web client calls the dynamically generated js format file (usually with JSON as the suffix) on the cross-domain server in exactly the same way as the calling script. Obviously, the server needs to dynamically generate JSON files, The purpose is to load the data that the client needs into it.

  6. After the client successfully calls the JSON file, it also obtains the data it needs, and the rest is to process and display it according to its own needs. This method of obtaining remote data looks very similar to AJAX, but it does not Same.

  7. In order to facilitate the client to use the data, an informal transmission protocol has gradually formed, which is called JSONP. One of the main points of the protocol is to allow the user to pass a callbackparameter to the server, and then the server returns the data. This callbackparameter is used as The function name wraps the JSON data, so that the client can customize its own function to automatically process the returned data.

If there is still some vagueness about how to use the callback parameter, we will have a specific example to explain it later.

The specific implementation of the JSONP client:

Regardless of whether it is jQuery, extjs, or other frameworks that support jsonp, the work they do behind the scenes is the same. Let me explain the implementation of jsonp on the client side step by step:

1. We know that even if the code in the cross-domain js file (of course, it refers to the web script security policy), the web page can be executed unconditionally.

remoteserver.comThere is a file in the root directory of the remote server with the remote.jsfollowing code:

alert('我是远程文件');

localserver.comThere is a jsonp.htmlpage code under the local server 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 window will pop up on the page, showing that the cross-domain call was successful.

2. Now we jsonp.htmldefine a function on the page, and then call it by passing in data in the remote remote.js.

jsonp.htmlThe 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('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
    };
    </script>
    <script type="text/javascript" src="http://remoteserver.com/remote.js"></script>
</head>
<body>

</body>
</html>

remote.jsThe file code is as follows:

localHandler({"result":"我是远程js带来的数据"});

After running, check the result, the page successfully pops up a prompt window, showing that the local function was successfully called by the cross-domain remote js, and also received the data brought by the remote js. I am very happy, the purpose of obtaining data remotely across domains has been basically achieved, but another question has arisen, how can I let the remote js know the name of the local function it should call? After all, jsonp's server has to face many service objects, and the local functions of these service objects are different? Let's look down.

3. It is easy for smart developers to think that as long as the js script provided by the server is dynamically generated, the caller can pass a parameter to tell the server "I want a js code that calls the XXX function, please. Return to me", so the server can generate the js script and respond according to the client's needs.

Look at jsonp.htmlthe code of the 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">
    // 得到航班信息查询结果后的回调函数
    var flightHandler = function(data){
        alert('你查询的航班结果是:票价 ' + data.price + ' 元,' + '余票 ' + data.tickets + ' 张。');
    };
    // 提供jsonp服务的url地址(不管是什么类型的地址,最终生成的返回值都是一段javascript代码)
    var url = "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler";
    // 创建script标签,设置其属性
    var script = document.createElement('script');
    script.setAttribute('src', url);
    // 把script标签加入head,此时调用开始
    document.getElementsByTagName('head')[0].appendChild(script); 
    </script>
</head>
<body>

</body>
</html>

The code change this time is relatively large. Instead of directly writing the remote js file to death, the code implements dynamic query, which is also the core part of the jsonp client implementation. The focus in this example is how to complete the jsonp call the whole process.

We see that a codeparameter is passed in the called url, telling the server that I want to check the information of flight CA1998, and the callbackparameter tells the server that my local callback function is called flightHandler, so please pass the query result into this function to call .

OK, the server is very smart, this called flightResult.aspxpage generates a piece of code like this and provides it to jsonp.html(the implementation of the server will not be demonstrated here, it has nothing to do with the language you choose, in the final analysis, it is splicing strings):

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

We see that what is passed to the flightHandlerfunction is a json that describes the basic information of the flight. Run the page, a prompt window pops up successfully, and the whole process of jsonp execution is successfully completed!

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

What? You are using jQuery, wondering how jQuery implements jsonp calls? Well, then I'll do it to the end, and give you a piece of jQuery code using jsonp (we still use the example of the flight information query above, assuming the return jsonp result 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",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
             success: function(json){
                 alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
             },
             error: function(){
                 alert('fail');
             }
         });
     });
     </script>
     </head>
  <body>
  </body>
 </html>

Is it a little strange? Why didn't I write flightHandlerthis function this time? And it actually worked! Haha, this is the credit of jQuery. When jquery handles jsonp type ajax (still can't help but complain, although jquery also classifies jsonp into ajax, but in fact they are not the same thing), it automatically generates for you Isn't it cool to call back the function and take out the data for the successproperty method to call?

Well, writing this, I have been unable to write any more, I am sleepy and tired, and I have to go to bed quickly. If friends see this well and feel inspired, please give me a "recommendation"! Because it is relatively simple, the demo source code download is no longer provided.

Replenish:

  1. The two technologies, ajax and jsonp, "look" very similar in terms of calling methods, and the purpose is the same. They both request a url and then process the data returned by the server. Therefore, frameworks such as jquery and ext use jsonp as a part of ajax. encapsulated in various forms;

  2. But ajax and jsonp are essentially different things. The core of ajax is to XmlHttpRequestobtain non-this page content, and the core of jsonp is to dynamically add <script>tags to call the js script provided by the server.

  3. Therefore, in fact, the difference between ajax and jsonp is not whether it is cross-domain. Ajax can also achieve cross-domain through server-side proxy, and jsonp itself does not exclude the acquisition of data in the same domain.

  4. In addition, jsonp is a method or a non-mandatory protocol. Like ajax, it does not necessarily have to use json format to transmit data. If you want, strings can be used, but it is not conducive to using jsonp to provide data. public service.

All in all, jsonp is not a special case of ajax, even if jquery and other giants encapsulate jsonp into ajax, it cannot change a little!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325589324&siteId=291194637