What is JSON and JSONP, jQuery JSON instances in detail in detail

JSON can describe the data structure in a very simple way, and XML can do it, so there is no distinction between the two in terms of cross -platform. In fact, there are many explanations about JSONP on the Internet. Let’s explain this problem to see if it is helpful
What is JSON?
The previous briefly, JSON is a text -based data exchange method, or the data description format. Do you choose that he must first pay attention to the advantages it has.

json’s advantages
1. Based on pure text, cross -platform transmission is extremely simple;
2, javascript native support, almost all support in the background language;
3. Lightweight data format, the number of characters is very small, especially suitable for Internet transmission;
4. Readability is strong. Although it is not as clear as XML, it is still easy to recognize after a reasonable interim;
5. Easy to write and analyze, of course, the premise is that you need to know the data structure;

The disadvantages of
json are of course there are, but to the author’s opinion, it is really unrelated, so it is no longer explained alone.

json format or rule
JSON can describe the data structure in a very simple way. The XML can do it, so the two are completely distinguished in terms of cross -platform.
1. JSON has only two types of data type descriptors, large brackets {} and square brackets []. The rest of the English colon: is a mapping symbol, an English comma, a separatist symbol, and a double quotation number “is a definition symbol.
2, large parentheses {} is used to describe a set of “different types of disorderly key values” (each key value pair of attribute descriptions that can be understood as OOP), square bracket [] is used to describe a set of “the same set of” the same set of “the same group Types of order -oriented data sets “(which can correspond to OOP array).
3. If there are multiple sub -items in the above two sets, they are separated by English commas.
4. The key value is separated in English colon: separate, and it is recommended that the key name adds English double quotes “” to facilitate the analysis of different languages.
5. The commonly used data types inside JSON are nothing more than a few string, numbers, Boolean, date, and NULL. The string must be caused by dual quotes. The rest are not used. The date type is relatively special. It is only recommended that if the client does not need to sort on the date, then the date time is passed directly as a string, which can save a lot of trouble.
json instance

Copy codecode is as follows:
// Describe a person
var person = {
“Name”: “Bob”,
“Age”: 32,
“Company”: “IBM”,
“Engineer”: true
}
// Get this person’s information
var personAge = person.Age;
// Describe a few 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 name of John’s company
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
}
]
}
// Whether to read the participant Henry whether the engineer
var henryIsAnEngineer = conference.Members[2].Engineer;

What is JSONP
In fact, there are many explanations about JSONP on the Internet, but they are the same, and in the clouds and fog, it is difficult to understand for many people who just contact. See if it is helpful.
1. A well -known question, AJAX directly requests the problem of cross -domain universal access to ordinary files.
2. However, we also found that when the JS file is called on the web page, it is not affected by whether it is cross -domain (not only that, we also find that the label of all the “SRC” attributes has cross -domain capabilities, such as <Script >, <IMG>, <iframe>);
3. So you can judge, if you want to pass the pure Web side (ActiveX control, server agent, websocket of HTML5 in the future), are not counted). Try to install the data in the JS format for client calling and further processing;
4. Coincidentally, we already know that there is a pure character data format called JSON.
5. In this way, the solution is desperate. The web client calls the JS format file (generally JSON as the suffix) by calling the dynamicly generated on cross -domain server by the same way as calling the script. The purpose of generating the JSON file is to install the data required by the client.
6. After the client is successfully called the JSON file, the data also obtains the data you need. The rest is processed and displayed according to your own needs. This method of obtaining remote data looks very much like AJAX. But it’s not the same.
7. In order to facilitate the use of data from the client, an informal transmission protocol has gradually formed. People call it JSONP. One of the main points of the protocol is to allow users to pass a callback parameter to the server, and then when the server returns the data, the server returns the data This callback parameter will be wrapped in JSON data as a function name, so that the client can customize its own functions from the motion processing and return data.
If it is still a bit vague for how to use the callback parameter, we will have a specific instance to explain.

jsonp client implementation
Regardless of jQuery, Extjs, or other frameworks that support JSONP, the work they do behind the scenes are the same. Let me gradually explain the realization of JSONP on the client:
1. We know that even if the code in the cross -domain JS file (of course refers to the web script security strategy), the web page can be executed unconditionally.
remote server remoteServer.com The root directory has a remote.js file code as follows:

Copy codecode is as follows:
Alert (‘I am a remote file’);

Local server localServer.com has a jsonp.html page code as follows: as follows:

Copy codecode 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 the page will pop up a prompt window to show that the cross -domain calls are successful.

2. Now we define a function on the jsonp.html page, and then call the data in the remote remote.js for calling.
jsonp.html page code is as follows:

Copy codecode 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 that can be called by cross -domain remote.js files. The data brought by the remote JS is:’ + data.Result);
};
</script>
<script type=”text/javascript” src=”http://remoteserver.com/remote.js”></script>
</head>
<body>
</body>
</html>

remote.js file code is as follows:

Copy codecode is as follows:
LocalHandler ({“result”: “I am the data brought by remote JS”});

After running, check the results. The page successfully pops up the prompt window, showing that the local function is successfully called by cross -domain remote JS, and it also receives data from remote JS. I am very happy. The purpose of cross -domain remote obtaining data is basically realized, but another problem has appeared. How can I let the remote JS know what the local function it should call? After all, the service of JSONP must face many service objects, and the local functions of these service objects are different? We look down.

3. Smart developers can easily think that as long as the JS script provided by the server is dynamically generated, so that the caller can pass a parameter to tell the server. Please return it to me “, so the server can generate the JS script according to the needs of the client and respond.
Look at the code of jsonp.html page:

Copy codecode 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”>
// The callback function after getting the results of the flight information query
var flightHandler = function(data){
Alert (‘The result you query flights is: fare’ + data.price +’ yuan, ‘ +’ remaining ticket ‘ + data.tickets +’ Zhang. ‘);
};
// URL address that provides JSONP services (no matter what type of address, the final return value is a section of JavaScript code)
var url = “http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler”;
// Create Script tags and set their attributes
var script = document.createElement(‘script’);
script.setAttribute(‘src’, url);
// Add the script tag to the head, and the call starts at this time
document.getElementsByTagName(‘head’)[0].appendChild(script);
</script>
</head>
<body>
</body>
</html>

This time the code changes is relatively large, and no longer directly write the remote JS file to death, but codes to achieve dynamic queries. This is also the core part of the JSONP client. The focus of this example is how to complete how to complete The whole process of JSONP calls.
We saw a code parameter in the call URL, telling the server that I want to check the information of the CA1998 flight, and the callback parameter tells the server. My local callback function is called Flighthandler, so please pass the query results into Call in this function.
OK, the server is very smart, this page called FlightResult.aspx generates a paragraph of this code to jsonp.html (the realization of the server is not demonstrated here, it has nothing to do with the language you chose. The

Copy codecode is as follows:
flightHandler({
“code”: “CA1998”,
“price”: 1780,
“tickets”: 5
});

We see that a JSON is passed to the Flighthandler function, which describes the basic information of the flight. Run the page, successfully pop up the prompt window, the entire process of JSONP is completed smoothly!

4. If you are here, I believe you can understand the principle of implementation of JSONP client? The rest is how to encapsulate the code in order to interact with the user interface, so as to achieve multiple and repeated calls.
What? You are using jQuery. Want to know how jQuery can implement JSONP calls? Well, then I will do it at the end, and give you a piece of jQuery using JSONP code (we still use the example of the above flight information query, assume that the results of the JSONP result remain unchanged):

Copy codecode 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=CA1998”,
dataType: “jsonp”,
jsonp: “callback”, // Pass to the request processing program or page for the parameter name of the JSONP callback function name (generally default: callback)
jsonpcallback: “Flighthandler”, // The customized JSONP callback function name, the default random function name of jquery automatically generated, can also write “?”, Jquery will automatically process data for you data
success: function(json){
Alert (‘You query flight information: fare:’ + json.price + ‘yuan, remaining ticket:’ + json.tickets + ‘Zhang.’);
},
error: function(){
alert(‘fail’);
}
});
});
</script>
</head>
<body>
</body>
</html>

Is it a bit strange? Why didn’t I write a Flighthandler function this time? And it was successful! Haha, this is the credit of jquery. When JQuery handles the JSONP type of AJAX (still can’t help voicing, although JQuery also attributed JSONP to AJAX, in fact, they are really not the same thing), automatically help you generate to generate generate Is it very cool to call the data and take out the data to call the SUCCESS attribute method?
Supplementary content
1, AJAX and JSONP technologies are “looking” very similar in the calling method. The purpose is the same. They all request a URL and then process the data returned by the server. Therefore A form of AJAX is encapsulated;
2, but Ajax and JSONP are actually different things. The core of AJAX is to obtain non -content on this page through XMLHTTPREQUEST, and the core of JSONP is to dynamically add a <Script> tag to call the JS script provided by the server.
3. So, in fact, the difference between AJAX and JSONP is not whether it is cross -domain. AJAX can also achieve cross -domain through server proxy, and JSONP itself does not exclude data acquisition in the same domain.
4, and there is, JSONP is a way or non -murmical protocol. Like AJAX, it does not necessarily need to pass data in JSON format. It is conducive to providing open services with JSONP.
In short, JSONP is not a special case of AJAX, even if JQuery and other giants encapsulate JSONP into AJAX, it cannot change a little!

Leave a Reply

Your email address will not be published. Required fields are marked *