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

Source: Internet
Author: User

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.

What is JSON?

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:

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.

JSON instance:

//describe a personvarperson = {"Name":"Bob","Age": +,"Company":"IBM","Engineer":true}//Get this person's informationvarpersonage = person. Age;//describe several peoplevarMembers = [{"Name":"Bob","Age": +,"Company":"IBM","Engineer":true},    {"Name":"John","Age": -,"Company":"Oracle","Engineer":false},    {"Name":"Henry","Age": $,"Company":"Microsoft","Engineer":false}]//Read the company name where JohnvarJohnscompany = members[1]. Company;//Describe one meetingvarconference = {"Conference":"Future Marketing","Date":"2012-6-1","Address":"Beijing","Members":     [        {"Name":"Bob","Age": +,"Company":"IBM","Engineer":true},        {"Name":"John","Age": -,"Company":"Oracle","Engineer":false},        {"Name":"Henry","Age": $,"Company":"Microsoft","Engineer":false}    ]}//Read attendee Henry whether engineervarHenryisanengineer = 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.

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(‘我是远程文件‘);

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 "><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 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 "><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, can be called by a cross-domain remote.js file, far    The data that the process JS brings is: ' + data.result);    };     </script>    <script type="text/javascript" src="http// Remoteserver.com/remote.js "></script></head><body></body></html>

The Remote.js file code is as follows:

localHandler({"result":"我是远程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 "><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title>    <script type="Text/javascript">    //Get the flight information callback function after query result    varFlighthandler = function(data){Alert' Your flight results are: Fares '+ Data.price +' Yuan, '+' remaining votes '+ Data.tickets +' Zhang. '); };//provide the URL address of the JSONP service (regardless of the type of address, the resulting return value is a piece of JavaScript code)    varURL ="Http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler";//Create a script tag, set its properties    varScript = Document.createelement (' script '); Script.setattribute (' src ', URL);//Add the script tag to head, at which point the call beginsdocument.getElementsByTagName (' head ')[0].appendchild (script);</script></head><body></body></html>

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 "> <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:falseUrl:"http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998", DataType:"Jsonp", Jsonp:"Callback",//passed to the request handler or page to obtain the parameter name of the JSONP callback function name (typically by default: callback)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 youSuccess function(JSON){Alert' You check flight information: Ticket price: '+ Json.price +' Yuan, more votes: '+ Json.tickets +' Zhang. '); }, Error: function(){Alert' fail ');     }         }); });</script>     </head>  <body>  </body> </html>

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?

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

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.