JSONP Implementing Data Cross-domain Requests

Source: Internet
Author: User
Tags script tag

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 the successful Cross-domain call

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 "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head>    <title></title>    <Scripttype= "text/javascript">    varLocalhandler= function(data) {alert ('I am a local function, can be called Cross-domain remote.js file, remote JS brings the data is:' +data.result);    }; </Script>    <Scripttype= "text/javascript"src= "http://remoteserver.com/remote.js"></Script></Head><Body></Body></HTML>

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 "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head>    <title></title>    <Scripttype= "text/javascript">    //callback function After getting the flight information query result    varFlighthandler= function(data) {alert ('The result of the flight you are inquiring for Is: ticket price' +Data.price+ 'yuan,' + 'remaining votes' +data.tickets+ 'of the Card. ');    }; //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, and the call startsdocument.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 "> <HTMLxmlns= "http://www.w3.org/1999/xhtml" > <Head>     <title>Untitled Page</title>      <Scripttype= "text/javascript"src=jquery.min.js "></Script>      <Scripttype= "text/javascript">jQuery (document). Ready (function() {$.ajax ({type:"Get", Async:false, Url:"http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998", DataType:"Jsonp", Jsonp:"Callback",//the parameter name that is passed to the request handler or page to obtain the name of the JSONP callback function (generally 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 you
Because the JSON file is requested, JSON is not a server-side dynamic language can not be parsed, if it is PHP or other server-side language, you do not have to write dead function namesuccess:function(json) {alert ('your flight information: fare:' +Json.price+ 'yuan, the remaining votes:' +json.tickets+ 'of the Card. '); }, error:function() {alert ('fail'); } }); }); </Script> </Head> <Body> </Body> </HTML>

The article is quoted from: "original" to say JSON and jsonp, perhaps you will be enlightened, including jquery use cases

JSONP Implementing Data Cross-domain Requests

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.