[Reprint] Let's Talk About JSON and jsonp. Maybe you will be very open, including jquery use cases.

Source: Internet
Author: User

Original blog:

Http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html

Preface:

 

Thanks to the features of the Development Mode sencha touch 2, it basically determines that its native data interaction behavior can only be achieved through Ajax.

Of course, by calling the powerful phonegap plug-in and packaging it, You can implement 100% socket communication and local database functions, you can also use HTML5 websocket to implement communication with the server and push the server. However, both methods have their own limitations. The former requires the support of phonegap, the latter requires that the user device must support websocket, so it cannot be regarded as the native solution of st2. The native only has Ajax.

 

Speaking of Ajax, there will inevitably be two problems. The first one is the format in which Ajax exchanges data? The second is how to solve the cross-origin requirement? Currently, these two problems have different solutions. For example, data can be described using custom strings or XML, and cross-origin can be solved through server-side proxy.

So far, the most popular or preferred solution is to use JSON to transmit data and use jsonp for cross-origin. This is what will be discussed in this article.

 

Although JSON and jsonp have only one letter, they are not the same thing at all: JSON is a data exchange format, jsonp is an unofficial cross-domain data interaction protocol created by the ingenuity of developers. Let's take the latest popular spy war films for example. JSON is the "Dark code" used by underground parties to write and exchange intelligence ", while jsonp is the connection method used to pass the information written in the dark signs to its comrades. See? One is the format of description information, and the other is the method agreed by both parties.

 

Since we can talk about it casually, we will not talk about it in a conventional way, but focus on helping developers understand whether they should choose to use it and how to use it.

A small advertisement. This article was written when I discussed the st2 Data Interaction Model with sencha touch 2 developers in my group,Therefore, if you are interested in mobile web app development, please joinSencha touch communicates with QQ Group 213119459.

 

What is JSON?

 

As mentioned above, JSON is a text-based data exchange method or a data description format. Whether to choose it 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, with almost all background languages supported;

3. lightweight data format, which occupies a very small number of characters and is especially suitable for Internet transmission;

4. Strong readability. Although not as clear as XML, it is easy to recognize after a proper indentation;

5. Easy to write and parse. The premise is that you must know the data structure;

Of course, there are also some disadvantages of JSON, but in the author's opinion, it is really irrelevant, so it is not described separately.

 

JSON format or rule:

JSON can describe the data structure in a very simple way. XML can be used to describe the data structure. Therefore, the two are completely different across platforms.

1. JSON only has two data type descriptors, braces {} and square brackets []. The remaining English colons are ing characters, English commas (,) are separators, and English double quotation marks (") are definitions.

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

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

4. Key-value pairs are separated by a colon (:). We recommend that you add double quotation marks (") to the key names for resolution in different languages.

5. Common Data Types in JSON are strings, numbers, Boolean values, dates, and null. strings must be enclosed in double quotation marks, and other data types are not used. The date type is special, I will not discuss it here, but it is recommended that if the client does not need to sort by date, it is better to pass the date and time directly as a string, which saves a lot of trouble.

 

JSON instance:

// Describe a person var person = {"name": "Bob", "Age": 32, "company": "IBM", "engineer ": true} // obtain the information of 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 the 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}]} // reads whether the participant Henry is an engineer var henryisanengineer = conference. members [2]. engineer;

 

For more details about JSON, refer to the document for further study during the development process.

 

What is jsonp?

 

Let's talk about how jsonp is generated:

In fact, there are a lot of explanations on jsonp on the Internet, but they are the same, and in the fog of the cloud, it is difficult for many people who have just been in touch to understand it, try to explain this problem in your own way and see if it is helpful.

1. A well-known problem is that AJAX directly requests common files without cross-domain access permissions. Render Manager determines that you are a static page, dynamic webpage, Web Service, and WCF, as long as it is a cross-domain request, no;

2. However, we found that when calling JS files on the web page, it is not affected by cross-origin (not only that, we also found that all tags with the "src" attribute have cross-domain capabilities, such as <SCRIPT>, , and <IFRAME> );

3. It can be determined that in the current stage, cross-Origin data access is only possible if you want to access data through pure web (ActiveX control, server proxy, websocket that belongs to HTML5 in the future, that is to say, on the remote server, try to put data into JS files for the client to call and further process;

4. We already know that there is a pure character data format called JSON that can describe complex data in a concise manner. Even better, JSON is also supported by JS native, therefore, the client can process data in this format as needed;

5. In this way, the solution is ready. The Web client uses the same method as the calling script to call the JS format files dynamically generated on the Cross-origin server (generally with the suffix of JSON). Obviously, the purpose of the server to dynamically generate a JSON file is to load the data required by the client.

6. After the client successfully calls the JSON file, it obtains the required data. The rest is to process and present the data as needed, this method of obtaining remote data looks like Ajax, but it is actually not the same.

7. In order to facilitate the use of data on the client, an informal transmission protocol is gradually formed, which is called jsonp. One key point of this Protocol is to allow users to pass a callback parameter to the server, then, when the server returns the data, the callback parameter is wrapped in JSON data as the function name, so that the client can customize its own function to automatically process the returned data.

If the callback parameter is still vague, we will introduce specific examples later.

The specific implementation of the jsonp client:

Regardless of jquery, extjs, or other frameworks that support jsonp, the work they do is the same. Next I will explain the implementation of jsonp on the client step by step:

 

1. We know that even the code in the Cross-origin JS file (of course, that complies with the web script Security Policy) can be executed unconditionally on the web page.

The remote server remoteserver.com root directory contains the following remote. js file code:

Alert ('am a remote file ');

The following figure shows the jsonp.html Page code of the worker server localserver.com:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

There is no doubt that a prompt form will pop up, showing that the cross-origin call is successful.

 

2. Now we define a function on the jsonp.html page, and then input data in remote. js for calling.

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"> 

The code of the remote. js file is as follows:

Localhandler ({"result": "data from remote JS "});

View the result after running. A Prompt window is displayed, indicating that the local function is successfully called by the cross-origin remote JS and that the data of the remote JS is received. I'm glad that the goal of cross-origin remote data retrieval is basically achieved, but another problem arises. How can I let remote JS know the name of the local function that should be called? After all, jsonp service providers have to deal with many 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 scripts provided by the server are dynamically generated, in this way, the caller can pass a parameter and tell the server that "I want a JS Code to call the xxx function. Please return it to me ", as a result, the server can generate JS scripts and respond to the requirements of the client.

View 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"> 

The code changes a lot this time, instead of Directly Writing remote JS files to death, but coding for dynamic query, which is also the core part of jsonp client implementation, the focus of this example is how to complete the entire jsonp call process.

We can see that a code parameter is passed in the called URL, telling the server that I want to check information about the 98 flights, while the callback parameter tells the server that my local callback function is called flighthandler, therefore, pass the query results to this function for calling.

OK ,the server is very intelligent. This code is generated on the page of flightresult.aspxand sent to jsonp.html (the implementation of the server is not demonstrated here. It has nothing to do with the language you choose. In the end, it is a concatenation string ):

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

We can see that what is passed to the flighthandler function is a JSON that describes the basic information of the flight. Run the page. A Prompt window is displayed. The jsonp execution process is successfully completed!

 

4. So far, I believe you can understand the implementation principles of the jsonp client? The rest is how to encapsulate the Code to facilitate interaction with the user interface, so as to implement multiple and repeated calls.

What? You are using jquery. How does jquery implement jsonp calling? Okay, let me look at it and give you another piece of code for jquery to use jsonp (we still use the example of the Flight Information Query above, assuming that the return result of 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"> $. Ajax ({type: "Get", async: false, URL: "http://flightQuery.com/jsonp/flightResult.aspx? Code = 98 ", datatype:" jsonp ", jsonp:" Callback ", //, the parameter name used to obtain the jsonp callback function name (usually callback by default) jsonpcallback: "flighthandler", // The Custom jsonp callback function name, the default value is the random function name automatically generated by jquery. You can also enter "? ", Jquery will automatically process the data for you. Success: function (JSON) {alert ('your queried flight information: Fare: '+ JSON. price + 'yuan, remaining ticket: '+ JSON. tickets +. ') ;}, Error: function () {alert ('fail ');}});}); </SCRIPT> 

Isn't it strange? Why didn't I write the flighthandler function this time? And the operation was successful! Haha, this is jquery's credit. When jquery is dealing with jsonp-type Ajax (it can't help but vomit, although jquery also classifies jsonp as Ajax, but they are really not the same thing.) Is it nice to automatically generate a callback function and extract the data for the success attribute method to call?

 

Well, I can't write it here. I'm sleepy and tired, so I have to go to bed. If you think this is good, I think it is inspiring. Please give me a "recommendation! Because it is relatively simple, the demo source code download is no longer provided.

 

Supplement on the afternoon of April 9:

 

I did not expect the headline recommendation from the blog Park. I am very happy to see everyone's comments and comments on this article. Here I will make some additional remarks on the similarities and differences between Ajax and jsonp:

1. Ajax and jsonp are similar in calling methods, with the same purpose. They both request a URL and process the data returned by the server, therefore, jquery and ext both use jsonp as a form of Ajax encapsulation;

2. Ajax and jsonp are essentially different. The core of AJAX is to use XMLHttpRequest to obtain content not on this page, while the core of jsonp is to dynamically Add the <SCRIPT> tag to call the JS script provided by the server.

3. Therefore, in fact, the difference between Ajax and jsonp is not whether to cross-origin. Ajax can implement cross-origin through the server proxy, and jsonp itself does not reject data acquisition from the same domain.

4. Also, jsonp is a method or a non-mandatory protocol. Like Ajax, jsonp does not have to transmit data in JSON format. If you want to, the string will work, however, this is not conducive to using jsonp to provide public services.

All in all, jsonp is not a special case of Ajax. Even if jquery and other giants encapsulate jsonp into Ajax, it cannot be changed!

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.