Say a word about JavaScript cross-domain and JSONP

Source: Internet
Author: User
Tags script tag domain server

Homologous policy

In the browser's security policy, "homologous policy" is very thunderclap piercing, that is, the protocol, domain name, the same port as the same origin, the domain name can also be replaced by an IP address, the non-homologous page script can not obtain the other party's data.

If you want to use XMLHttpRequest or a regular Ajax request to get data from another site, the browser will tell you "XXXX is not allowed by access-control-allow-orign".

Because of the existence of homologous policy, the security problem of cross-domain access is prevented, but also the convenience of convenient access to resources is lost.

cross-domain src attribute

The world is not absolute, the browser still allows several elements to access external resources across domains, such as: <script>,,<iframe>, that is, elements that have SRC attributes in HTML elements are resources that can be accessed across domains.

Through the SRC attribute, IMG can refer to other sites or pictures of the bed, greatly reducing the image of this site lasting.

Through the SRC attribute, script can reference the CDN JS file, accelerate the browser's script file download, cross-domain data acquisition more efficient and convenient.

Through the SRC attribute, the IFRAME can be embedded in other sites of the page, can make the page frame and variable content separation, content reference more flexible, easy to reference other sites, although it is increasingly not recommended to use it.

Because of the existence of cross-domain access, the Web world can be more exciting.

JSONP formally exploited the cross-domain capability of the script tag.

JSONP

Full name JSON with padding

is to access the data on a cross-domain server by convention.

This convention is actually a function definition, and has the definition of data parameters, called by a cross-domain server script or dynamically generated script, and pass data parameters.

This function is called a "cross-domain callback function".

1. A simple cross-domain scripting call

A script on the local server that directly references a script file on a cross-domain server.

<HTML><Head>    <title>Test</title></Head><Body>    <Scriptsrc= "Http://localhost:3001/javascripts/jsonpsrc1.js"></Script></Body></HTML>

Script jsonpsrc1.js on a cross-domain server

Alert (' Hi we're not a domain's Oh ');

After running, the browser accesses the page on the local server and will pop up alert

2. Cross-domain data transfer

In the script of the local server, contract a function called Jsonpcallback cross-Domain callback function referred to a script on a cross-domain server.

Note that the Jsonpcallback cross-domain callback function must be defined before referencing a script on a cross-domain server.

<HTML><Head>    <title>Test</title></Head><Body><Script>    functionJsonpcallback (data) {alert (json.stringify) (data,NULL,2)); }</Script><Scriptsrc= "Http://localhost:3001/javascripts/jsonpsrc2.js"></Script></Body></HTML>

Script jsonpsrc2.js on a cross-domain server, called by the Convention's cross-domain callback function name, and passes a data object.

Jsonpcallback ({    name: ' White Sea ',    age:90});

After running, the browser accesses the page on the local server, and an alert pops up to show the data passed across the domain server.

3. Dynamic cross-Domain callback function

Using the above 2 methods has basically implemented the use of JSONP, but there is still a problem, it is necessary to pre-contract the cross-domain callback function name.

It is extremely inconvenient to define each time as a callback function name on a cross-domain server.

Then two cross-domain script references can not bind the same function name.

You can arbitrarily define the name of a cross-domain callback function in the local server script, request the function name with parameters to cross-domain servers, dynamically stitch the call string of the callback function on the cross-domain server backend code and respond to the requester.

Here is a simple implementation using the NODE.JS+EXPRESS environment and a simple cross-domain request to query flight information.

The Showflightinfo cross-domain callback function is defined in the local Server page script to display the flight information returned by the cross-domain server.

A JS request is made to the cross-domain server in the script tag that follows, and the flight information and the cross-domain callback function name are taken over.

<HTML><Head>    <title>Test</title>    <Linkrel= "stylesheet"href= "/stylesheets/style.css"></Head><Body>    <H1>Flight information</H1>    <H1>An airline</H1>    <Script>        functionShowflightinfo (data) {varFlightnoele=Document.createelement ('h4'); Flightnoele.innerhtml=Data.flightno; varFromele=Document.createelement ('h4'); Fromele.innerhtml=Data.from; varToele=Document.createelement ('h4'); Toele.innerhtml=data.to;            Document.body.appendChild (Flightnoele);            Document.body.appendChild (Fromele);        Document.body.appendChild (Toele); }    </Script>    <Scriptsrc= "http://localhost:3001/info/flight?flightno=mu531&callbackfunc=showflightinfo"></Script></Body></HTML>

Cross-domain server in the background code in response to JS request, receive flight number, generate flight information, together with the cross-domain callback function name stitching into a JS string after the response to the requester.

Router.get ('/info/flight ',function(req, res) {//generate flight information, and here you'll get the flight number you requested to write a flight information object .    vardata ={flightNo:req.query.flightNo, from:Beijing, to:Shanghai}; //Gets the cross-domain callback function name that was requested .    varCallbackfunc =Req.query.callbackFunc; //To spell a JS string     var s = callbackfunc + ' (' + json.stringify (data, null, 2) + '); ';    Console.log (s); //by setting the header of the HTTP, tell the requester that the content of the response is the JS scriptRes.setheader (' Content-type ', ' text/javascirpt;charset=utf-8 '); //res.setheader (' content-language ', ' ZH-CN ')Res.write (s); Res.end ();});

After running, the browser accesses the page on the local server and displays the flight information that is uploaded by the cross-domain server.

In order to see clearly, the content of requests and responses received by cross-domain servers is output to the console for easy viewing.

The first line is the received request, followed by the response to the request, you can see the cross-domain service side returned to the requester a JS script, where the callback function name is requester-customized.

This completes the basic implementation of JSONP.

It's not just jsonp.

Obtaining data through cross-domain requests essentially leverages the SRC attribute of the <script> tag to pull the cross-domain script through the browser and execute simultaneously.

Well, since it's pulled over, that's not much different from the execution of the other scripts on this page, it's also possible to change the way the page is displayed by generating HTML elements and CSS to achieve richer functionality, such as advertising.

Based on the flight information above, I'm going to display a piece of advertising content from a cross-domain server.

referencing the corresponding AD resource address on a cross-domain server via the <script> tag

<HTML><Head>    <title>Test</title>    <Linkrel= "stylesheet"href= "/stylesheets/style.css"></Head>    <Body>        <H1>Flight information</H1>         <script  src= "Http://localhost:3001/ad"></Script  >         <H1>An airline</H1>        <Script>            functionShowflightinfo (data) {varFlightnoele=Document.createelement ('h4'); Flightnoele.innerhtml=Data.flightno; varFromele=Document.createelement ('h4'); Fromele.innerhtml=Data.from; varToele=Document.createelement ('h4'); Toele.innerhtml=data.to;                Document.body.appendChild (Flightnoele);                Document.body.appendChild (Fromele);            Document.body.appendChild (Toele); }        </Script>        <Scriptsrc= "Http://localhost:3001/info/flight?flightNo=MU531&amp;callbackFunc=showFlightInfo"></Script>    </Body></HTML>

The cross-domain server's backend code responds to the JS request, generating a string that uses document.write to generate HTML elements into the page.

function (req, res) {    // splicing A JS string, complete outputting HTML markup to HTML page     var s = ' document.write ( \ ' <div style= "Background-color:red;width:10rem;height:10rem" > I am a travel agency advertising </div>\ '); ' ;    Console.log (s);    Res.setheader (' content-type ', ' text/javascirpt;charset=utf-8 ');    Res.write (s);    Res.end ();});

After running, the browser accesses the page on the local server and displays a red ad bit below the flight information, which is generated entirely across domain servers and includes styles.

On this basis, a number of effects can be made, including the generation of a part of the page to a dedicated or corresponding business Server to complete.

Say a word about JavaScript cross-domain and JSONP

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.