JSON and JSONP, maybe you'll be enlightened, with jquery use cases

Source: Internet
Author: User
Tags script tag domain server

Objective:

When it comes to Ajax, it inevitably faces two problems, the first of which is what format does AJAX exchange data for? The second is how do cross-domain requirements work? Both problems now have different solutions, such as data can be described by a custom string or XML, and cross-domain can be resolved by a server-side proxy.

But the best-known or preferred solution so far is to use JSON to spread data across domains by JSONP. And that's what this article is going to tell you.

JSON and JSONP Although there is only one letter difference, but actually they are not the same thing: JSON is a data interchange format, and Jsonp is a kind of unofficial cross-domain data interaction protocol that relies on the ingenuity of developers. We use the latest spy war film to make an analogy, JSON is used by the underground to write and exchange information "code", and Jsonp is the message written with the signal to his comrades using the connection method. Did you see that? One is the format of describing information, and the other is the method agreed by both parties to the information delivery.

Since we are talking casually, we are not going to use dogma to tell, but focus on helping developers understand whether they should choose to use and how to use them.

what is JSONP?

In a nutshell, JSON is a text-based data exchange, or a data description format, and you should choose whether or not he should first focus on the advantages it has.

The advantages of JSON:

1, based on plain text, cross-platform transmission is extremely simple;

2, JavaScript native support, background language almost all support;

3, lightweight data format, occupies very few characters, especially suitable for internet transmission;

4, readability is strong, although less than the XML so at a glance, but in a reasonable order after indentation is easy to identify;

5, easy to write and analysis, of course, if you want to know the data structure;

The format or rule of JSON:

JSON can describe a data structure in a very simple way, and XML can do it all, so it's completely pitches in cross-platform terms.

1. JSON has only two data type descriptors, curly braces {} and square brackets [], the remaining English colons: is the map, comma, is the delimiter, the English double quotation mark "" is the definition.

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

3, if there are more than one of the two sets of children, it is separated by commas.

4. The key value pairs are separated by a colon: and the key name is suggested with the English double quotation mark "" to facilitate the parsing of different languages.

5, JSON internal data type is nothing more than string, number, Boolean, date, null so several, the string must be enclosed in double quotation marks, the rest are not, the date type is special, here does not expand the narrative, but it is recommended if the client is not sorted by date function requirements, It would be nice to pass the date and time directly as a string, which would save a lot of trouble.

JSON instance:

Describe a person var man = {"Name": "Bob", "age": +, "Company": "IBM", "Engineer": true}//get this person's information var personage = Person.    age;//describes several people var members = [{' Name ': ' Bob ', ' age ': +, ' company ': ' IBM ', ' Engineer ': true        }, {"Name": "John", "age": +, "Company": "Oracle", "Engineer": false}, { "Name": "Henry", "Age": $, "Company": "Microsoft", "Engineer": false}]//read where John's name is Var Johns Company = Members[1].    company;//describes a meeting var conference = {"conference": "Future Marketing", "Date": "2012-6-1", "Address": "Beijing", "Members": [{"Name": "Bob", "age": +, "Company": "IBM", "Engin            EER ": true}, {" Name ":" John "," age ": +," Company ":" Oracle ", "Engineer": false}, {"Name": "Henry", "Age": $, "Company": "MicrosoFT "," Engineer ": false}]}//Read attendee Henry whether engineer var Henryisanengineer = conference. MEMBERS[2]. Engineer;

About JSON, that's all, more details, please consult the information in the development process in-depth study.

What is JSONP?

Let's talk about how JSONP is produced:

In fact, there are a lot of jsonp on the Internet, but the uniform, and foggy, for many people just contact to understand some difficulties, small not only, try to use their own way to explain the problem, see if it helps.

1, a well-known problem, Ajax directly request ordinary file There is no access to cross-domain issues, no matter you are static pages, dynamic Web pages, Web services, WCF, as long as the cross-domain requests, are not allowed;

2, but we also found that the Web page when the JS file is not affected by whether or not cross-domain impact (not only that, we also found that the "src" attribute of the label has the ability to cross-domain, such as <script>, , <iframe >);

3, so can judge, the current stage if you want to through the pure Web side (ActiveX control, Server Agent, belongs to the future of HTML5 WebSocket, etc.) access to data across domains is only one possibility, that is, on the remote server to try to load the data into the JS format of the file, For client invocation and further processing;

4, it happens that we already know that there is a kind of pure character data format called JSON can be concise description of complex data, even better is the JSON is also supported by JS native, so in the client can almost arbitrary processing of this format of data;

5, such a solution is to be seen, the Web client by the same way as the call script to invoke the cross-domain server dynamically generated JS format files (usually JSON suffix), it is obvious that the server to dynamically generate JSON files, The goal is to load the data that the client needs.

6, the client in the JSON file after the successful call, but also to obtain their own required data, the rest is to do their own needs to deal with and show that the way to get remote data looks very much like Ajax, but in fact, it is not the same.

7, in order to facilitate the use of data by the client, gradually formed an informal transport protocol, people call it Jsonp, one of the main points of the protocol is to allow users to pass a callback parameter to the server, The callback parameter is then used as the function name to wrap the JSON data when the server returns data, so that the client can customize its own function to automatically process the returned data.

If there is some ambiguity about how the callback parameter is used, there are specific examples to explain later.

JSONP Client-specific implementations:

No matter jquery or ExtJS, or other support JSONP framework, they do the work behind the scenes are the same, I would like to gradually explain the JSONP in the client implementation:

1. We know that even if the code in the cross-domain JS file (which is, of course, conforms to the Web Scripting Security Policy), the Web page can be executed unconditionally.

The remote server remoteserver.com root directory has a remote.js file code as follows:

Alert (' I am a remote file ');

There is a jsonp.html page code below the local 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 the page will pop up a prompt form that shows cross-domain invocation success.

2. Now we define a function on the jsonp.html page and then pass in the data in the remote Remote.js to make the call.

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

The Remote.js file code is as follows:

Localhandler ({"Result": "I am the data brought by remote JS"});

After running to view the results, the page successfully pops up the prompt window, showing that the local function was successfully cross-domain remote JS call, and also received the data from the remote JS. Happily, the goal of cross-domain remote data acquisition is basically realized, but another problem arises, how can I let remote JS know what the local function it should call called? After all, JSONP service providers have to face a lot of service objects, and these service objects are different local functions? We went on to look down.

3, smart developers are very easy to think, as long as the server provided by the JS script is dynamically generated on the line, so that callers can pass a parameter in the past to tell the service side "I want a call xxx function JS Code, please return to me", so the servers can follow the client's needs to generate JS script and response.

Look at the code for the jsonp.html page:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

This time the code changes relatively large, no longer directly to the remote JS file to write dead, but the code to implement dynamic query, and this is the core part of the JSONP client implementation, the focus of this example is how to complete the JSONP call the whole process.

We see the URL of the call passed a code parameter, tell the server I want to check the CA1998 flight information, and the callback parameter tells the server, my local callback function is called Flighthandler, so please pass the query results into this function to call.

OK, the server is very smart, this is called Flightresult.aspx Page generated a section of this code to provide to jsonp.html (service-side implementation is not demonstrated here, and you choose the language regardless of, in the final analysis is stitching strings):

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

As we can see, a JSON is passed to the Flighthandler function, which describes the basic information of the flight. Run the page, the successful pop-up prompt window, JSONP implementation of the entire process completed successfully!

4, so far, I believe you have been able to understand the JSONP of the client implementation of the principle of it? The rest is how to encapsulate the code to make it easier to interact with the user interface for multiple and repeated calls.

What the? You're using jquery, and you want to know how jquery implements JSONP calls? Well, then I'll give you a good one. jquery uses the JSONP code (we still use the example of the flight information query above, assuming the return JSONP result is the same):

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> $.ajax ({type: "Get", Async:false, url: "http://flightQuery.com/jsonp/flightResult.as px?code=ca1998 ", DataType:" Jsonp ", Jsonp:" Callback ",//passed to the request handler or page, to obtain the name of the JSONP callback function name (generally by default: Cal             Lback) Jsonpcallback: "Flighthandler",///Custom JSONP callback function name, default to jquery automatically generated random function name, can also write "?", jquery will automatically process the data for you Success:function (JSON) {alert (' You inquire about flight information: fare: ' + Json.price + ' yuan, more than a ticket: ' + json.tickets + ' Zhang.             ‘);             }, Error:function () {alert (' fail ');     }         });     }); </script> 

Isn't it a little strange? Why didn't I write this flighthandler function this time? And it worked! Haha, this is the credit of jquery, jquery in the processing of JSONP type of Ajax (or can not help to spit groove, although jquery also put Jsonp into Ajax, but in fact, they really are not a thing), Is it cool to automatically generate callback functions for you and take the data out for the Success property method to invoke?

For the similarities and differences between Ajax and JSONP to do some additional explanation:

1, Ajax and JSONP the two technologies in the invocation of the way "looks" very much like, the purpose is the same, is to request a URL, and then the server to return the data processed, so the jquery and ext and other frameworks have Jsonp as a form of Ajax encapsulation;

2, but Ajax and JSONP are actually different things in nature. The core of Ajax is to obtain non-page content through XMLHttpRequest, while the core of JSONP is dynamic add <script> tag to invoke the JS script provided by the server.

3, so that, in fact, the difference between Ajax and JSONP is not whether cross-domain, AJAX through the service-side proxy can be implemented across domains, JSONP itself does not exclude the same domain data acquisition.

4, there is, Jsonp is a way or non-mandatory protocol, like Ajax, it does not have to use JSON format to pass the data, if you want to, the string is OK, but this is not conducive to the use of JSONP to provide public services.

All in all, JSONP is not a special case of Ajax, even if the giant jquery, such as Jsonp encapsulated in Ajax, can not change a bit!

This article is reproduced in http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html

JSON and JSONP, maybe you'll be enlightened, with jquery use cases

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.