Details about json, jsonp, and jQuery json instances

Source: Internet
Author: User

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:
Copy codeThe 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;


What is JSONP??
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.

Specific implementation of 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:
Copy codeThe Code is as follows:
Alert ('am a remote file ');

The following figure shows the jsonp.html Page code of the worker server localserver.com:
Copy codeThe 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" src = "http://remoteserver.com/remote.js"> </script>
</Head>
<Body>
</Body>
</Html>

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:
Copy codeThe 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 called by cross-origin remote. js files. The data that remote js brings is:' + data. result );
};
</Script>
<Script type = "text/javascript" src = "http://remoteserver.com/remote.js"> </script>
</Head>
<Body>
</Body>
</Html>

The code of the remote. js file is as follows:
Copy codeThe Code 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:
Copy codeThe 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">
// Callback function after obtaining the Flight Information Query Result
Var flightHandler = function (data ){
Alert ('the result of your query is: Fare '+ data. price +' yuan, '+ 'remaining pass' + data. tickets +. ');
};
// Provide the url address of the jsonp Service (no matter what type of address, the final returned value is a piece of javascript code)
Var url = "http://flightQuery.com/jsonp/flightResult.aspx? Code = coding 98 & callback = flightHandler ";
// Create a script tag and set its attributes
Var script = document. createElement ('script ');
Script. setAttribute ('src', url );
// Add the script tag to the head. The call starts.
Document. getElementsByTagName ('head') [0]. appendChild (script );
</Script>
</Head>
<Body>
</Body>
</Html>

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 ):
Copy codeThe Code is as follows:
FlightHandler ({
"Code": "000098 ",
"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 ):
Copy codeThe 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> 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 = 98 ",
DataType: "jsonp ",
Jsonp: "callback", // The parameter name that is passed to the request handler or page to obtain the jsonp callback function name (generally: callback by default)
JsonpCallback: "flightHandler", // custom jsonp callback function name. The default value is the random function name automatically generated by jQuery. You can also write it "? ", JQuery will automatically process the data for you
Success: function (json ){
Alert ('You found the flight information: Fare: '+ json. price +' yuan, remaining ticket: '+ json. tickets +. ');
},
Error: function (){
Alert ('fail ');
}
});
});
</Script>
</Head>
<Body>
</Body>
</Html>

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?
Supplementary content
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!

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.