Let's talk about JSON and JSONP. You may be very open. _ json-js tutorial

Source: Internet
Author: User
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 cross-origin requirements.

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.

JSON (JavaScript Object Notation) and JSONP (JSON with Padding) have only one letter, but 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.

   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:

The Code is as follows:


// 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 persons
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 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,); &lt;/P&gt; &lt;P&gt; 3. Therefore, you can determine whether to use a web Client (ActiveX control, server proxy, Websocket for HTML5 in the future) there is only one possibility of cross-origin access data, that is, try to put the data into the js format file on the remote server for the client to call and further process; &lt;/P&gt; &lt;P&gt; 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. &lt;/P&gt; &lt;P&gt; 5. This solution is ready for use. The web client uses the same method as calling the script, to call the js format files dynamically generated on the Cross-origin server (generally suffixed with JSON). Obviously, the server dynamically generates JSON files to load the data required by the client. &lt;/P&gt; &lt;P&gt; 6. After the client successfully calls the JSON file, it obtains the data it needs. 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. &lt;/P&gt; &lt;P&gt; 7. To facilitate the use of data on the client, an informal transmission protocol is gradually formed, which is called JSONP, one important aspect of this protocol is that users can pass a callback parameter to the server. When the server returns data, the callback parameter is used as the function name to enclose JSON data, in this way, the client can customize its own functions to automatically process the returned data. &lt;/P&gt; &lt;P&gt; If the callback parameter is ambiguous, we will explain it in detail. &lt;/P&gt; &lt;STRONG&gt; specific implementation of the JSONP client: &lt;/STRONG&gt; &lt;/P&gt; &lt;P&gt; no matter jQuery or ExtJs, or other frameworks that support jsonp, the work they do behind the scenes is the same. Next I will explain the implementation of jsonp on the client step by step: &lt;/P&gt; &lt;P&gt; 1. We know that even if the code in the Cross-origin js file (of course, compliant with the web script security policy), the web page can be executed unconditionally. &lt;/P&gt; &lt;P&gt; the remote server remoteserver.com root directory contains a remote. the js File Code is as follows: &lt;BR&gt; &lt;p class = "codetitle"&gt; &lt;U&gt; &lt;/U&gt; the code is as follows: &lt;/p&gt; &lt;p class = "codebody" id = "code57002"&gt; &lt;BR&gt; alert ('I am a remote file '); &lt;BR&gt; &lt;/p&gt; &lt;BR&gt; the following code is displayed on the jsonp.html page of the worker server localserver.com: &lt;BR&gt; &lt;p class = "codetitle"&gt; &lt;U&gt; &lt;/U&gt; the code is as follows: &lt;/p&gt; &lt;p class = "codebody" id = "code34976"&gt; &lt;BR&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;BR&gt; <ptml xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;BR&gt; <pead&gt; &lt;BR&gt; &lt;title&gt; &lt;/title&gt; &lt;BR&gt; &lt;script type =" text/javascript "src =" http://remoteserver.com/remote.js?1.1.23 "&gt; Script &lt;BR&gt; </pead&gt; &lt;BR&gt; &lt;body&gt; &lt;BR&gt; </ptml&gt; &lt;BR&gt; &lt;/p&gt; &lt;BR&gt; no doubt, A prompt is displayed, indicating that the cross-origin call is successful. &lt;Br&gt; 2. Now we define a function on the jsonp.html page, and then input data in remote. js for calling. &lt;Br&gt; the jsonp.html Page code is as follows: &lt;BR&gt; &lt;p class = "codetitle"&gt; &lt;U&gt; &lt;/U&gt; the code is as follows: &lt;/p&gt; &lt;p class = "codebody" id = "code74497"&gt; &lt;BR&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;BR&gt; <ptml xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;BR&gt; <pead&gt; &lt;BR&gt; &lt;title&gt; &lt;/title&gt; &lt;BR&gt; &lt;script type =" text/javascript "&gt; &lt;BR&gt; var localHandler = function (data) {&lt;BR&gt; alert ('I am a local function and can be cross-origin remote. js file call. The remote js data is: '+ data. result); &lt;BR &gt;}; &lt;BR&gt; script &lt;BR&gt; &lt;script type = "text/javascript" src =" http://remoteserver.com/remote.js?1.1.23 "&gt; Script &lt;BR&gt; </pead&gt; &lt;BR&gt; &lt;body&gt; &lt;BR&gt; </ptml&gt; &lt;BR&gt; &lt;/p&gt; &lt;BR&gt; remote. the js File Code is as follows: &lt;BR&gt; &lt;p class = "codetitle"&gt; &lt;U&gt; &lt;/U&gt; the code is as follows: &lt;/p&gt; &lt;p class = "codebody" id = "code55934"&gt; &lt;BR&gt; localHandler ({"result": "data from remote js "}); &lt;BR&gt; &lt;/p&gt; &lt;BR&gt; View the result after running. A Prompt window is displayed, indicating that the local function is successfully called by cross-origin remote js, it also receives data from remote js. 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. &lt;Br&gt; 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. &lt;Br&gt; View the code on the jsonp.html page: &lt;BR&gt; &lt;p class = "codetitle"&gt; &lt;U&gt; &lt;/U&gt; the code is as follows: &lt;/p&gt; &lt;p class = "codebody" id = "code38181"&gt; &lt;BR&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;BR&gt; <ptml xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;BR&gt; <pead&gt; &lt;BR&gt; &lt;title&gt; &lt;/title&gt; &lt;BR&gt; &lt;script type =" text/javascript "&gt; &lt;BR&gt; // query flight information. callback function after result &lt;BR&gt; var flightHandler = function (data) {&lt;BR&gt; alert ('your query result is: Fare '+ data. price + 'yuan, '+ 'remaining votes' + data. tickets +. '); &lt;BR &gt;}; &lt;BR&gt; // provide the url address of the jsonp Service (no matter what type of address, the final return value is a piece of javascript code) &lt;BR&gt; var url =" http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998 &amp; Callback = flightHandler "; &lt;BR&gt; // create a script tag and set its attributes. &lt;BR&gt; var script = document. createElement ('script'); &lt;BR&gt; script. setAttribute ('src', url); &lt;BR&gt; // Add the script tag to the head. The call starts. &lt;BR&gt; document. getElementsByTagName ('head') [0]. appendChild (script ); &lt;BR&gt; script &lt;BR&gt; </pead&gt; &lt;BR&gt; &lt;body&gt; &lt;BR&gt; </ptml&gt; &lt;BR&gt; &lt;/p&gt; &lt;BR&gt; the code changes a lot this time, no longer Directly Writing remote js files to death, but encoding for dynamic query, which is also the core part of the jsonp client implementation. The focus in this example is how to complete the whole process of jsonp calls. &lt;Br&gt; we can see that a code parameter is passed in the called url, telling the server what I want to query is the information of the 98 flights, while the callback parameter tells the server, my local callback function is called flightHandler, so please pass the query result into this function for calling. &lt;Br&gt; OK ,the server is very intelligent. The page calling flightresult.aspxgenerates a code example for jsonp.html (the server implementation is not demonstrated here. It has nothing to do with the language you selected. In the end, it is a concatenation string ): &lt;BR&gt; &lt;p class = "codetitle"&gt; &lt;U&gt; &lt;/U&gt; the code is as follows: &lt;/p&gt; &lt;p class = "codebody" id = "code64884"&gt; &lt;BR&gt; flightHandler ({&lt;BR&gt; "code": "000098 ", &lt;BR&gt; "price": 1780, &lt;BR&gt; "tickets": 5 &lt;BR &gt;}); &lt;BR&gt; &lt;/p&gt; &lt;BR&gt; we can see that, the flightHandler function is passed in json, which describes the basic flight information. Run the page. A Prompt window is displayed. The jsonp execution process is successfully completed! &lt;Br&gt; 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. &lt;Br&gt; 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 ): &lt;BR&gt; &lt;p class = "codetitle"&gt; &lt;U&gt; &lt;/U&gt; the code is as follows: &lt;/p&gt; &lt;p class = "codebody" id = "code84774"&gt; &lt;BR&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;BR&gt; <ptml xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;BR&gt; <pead&gt; &lt;BR&gt; &lt;title&gt; Untitled Page &lt;/title&gt; &lt;BR&gt; &lt;script type =" text/javascript "src = jquery. min. js? 1.1.23 "&gt; script &lt;BR&gt; &lt;script type =" text/javascript "&gt; &lt;BR&gt; jQuery (document ). ready (function () {&lt;BR&gt; $. ajax ({&lt;BR&gt; type: "get", &lt;BR&gt; async: false, &lt;BR&gt; url :" http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998 ", &lt;BR&gt; dataType:" jsonp ", &lt;BR&gt; jsonp:" callback ", // The one that is passed to the request handler or the page, the parameter name used to obtain the jsonp callback function name (generally: callback by default) &lt;BR&gt; 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 &lt;BR&gt; success: function (json) {&lt;BR&gt; alert ('the flight information you have found: Fare: '+ json. price + 'yuan, remaining ticket: '+ json. tickets +. '); &lt;BR &gt;}, &lt;BR&gt; error: function () {&lt;BR&gt; alert ('fail'); &lt;BR &gt;}&lt; BR&gt; }); &lt;BR&gt; }); &lt;BR&gt; script &lt;BR&gt; </pead&gt; &lt;BR&gt; &lt;body&gt; &lt;BR&gt; </ptml&gt; &lt;BR&gt; &lt;/p&gt; &lt;BR&gt; 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?

Related Article

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.