JavaScript cross-domain Method learning Summary

Source: Internet
Author: User
Tags script tag domain server subdomain

JavaScript cross-domain:

Url

Description

Whether to allow communication

Http://www.a.com/a.js
Http://www.a.com/b.js

Under the same domain name

Allow

Http://www.a.com/lab/a.js
Http://www.a.com/script/b.js

Different folders under the same domain name

Allow

Http://www.a.com:8000/a.js
Http://www.a.com/b.js

Same domain name, different ports

Not allowed

Http://www.a.com/a.js
Https://www.a.com/b.js

Same domain name, different protocols

Not allowed

Http://www.a.com/a.js
Http://70.32.92.74/b.js

Domain and domain name corresponding IP

Not allowed

Http://www.a.com/a.js
Http://script.a.com/b.js

Primary domain is the same, subdomain is different

Not allowed

Http://www.a.com/a.js
Http://a.com/b.js

Same domain name, different level two domain name (IBID.)

Not allowed (cookies are also not allowed in this case)

Http://www.cnblogs.com/a.js
Http://www.a.com/b.js

Different domain names

Not allowed

JavaScript requests resources that are not part of their own domain, violating the same-origin policy, resulting in cross-domain.

(1) different protocols, such as HTTP and HTTPS.

(2) The domain name or IP is different.

(3) different ports.

Cross-Domain Solution:

1 , Script label cross-domain scenario.

The script tag does not have the same domain policy limit, and it is possible to get the scripts file across domains.

Client code:

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

<title></title>

<script type= "Text/javascript" >

var result = null;

Window.onload = function () {

var script = document.createelement ("script");

Script.type = "Text/javascript";

Script.src=\ ' #\ ' "//192.168.0.101/examplebusinessapplication.web/web2.aspx";

var head = document.getElementsByTagName ("head") [0];

Head.insertbefore (script, head.firstchild);

};

function callback (data) {

result = data;

}

function B_click () {

alert (result.name);

}

</script>

<body>

<input type= "button" value= "click me!" onclick= "B_click ();"/>

</body>

Service-Side code:

protected void Page_Load (object sender, EventArgs e)

{

string result = "Callback ({\" name\ ": \" zhangsan\ ", \" date\ ": \" 2012-12-03\ "})";

Response.Clear ();

Response.Write (Result);

Response.End ();

}

2 , Jsonp cross-domain scenarios.

The implementation principle of JSONP is the cross-domain mode of the script tag.

The JSONP cross-domain server and script tags are the same across domains, and return data in callback (+data+) format;

Service-Side code:

protected void Page_Load (object sender, EventArgs e)

{

String callback = request.querystring["Jsoncallback"];//Gets the callback method name from the request header

String result = Callback + "({\" name\ ": \" zhangsan\ ", \" date\ ": \" 2012-12-03\ "})";

Response.Clear ();

Response.Write (Result);

Response.End ();

}

Client code:

$.ajax ({

Async:false,

URL: "Http://192.168.0.5/Web/web1.aspx",

Type: "GET",

DataType: ' Jsonp ',

Jsonp the value of the custom, if using Jsoncallback, then the server side, to return a jsoncallback value corresponding to the object.

JSONP: ' Jsoncallback ',

To pass the parameter, do not pass the argument, also must write on

Data:null,

timeout:5000,

Return JSON type

ContentType: "Application/json;utf-8",

The object returned by the server segment contains the Name,data property.

Success:function (Result) {

alert (result.date);

},

Error:function (JQXHR, Textstatus, Errorthrown) {

alert (textstatus);

}

});

3 , Document.domain cross-subdomain scenarios.

The so-called cross-subdomain, is to set up document.domain two different domains of resources under the same parent domain, and then the two can interact normally.

A page code (http://www.example.com/a.html):

<script>

Document.domain = "example.com";

function aa () {

Alert ("P");

}

</script>

<body>

<iframe src=\ ' #\ ' "//example.com/b.html" id= "I" >

</iframe>

<script>

document.getElementById (' i '). onload = function () {

var d = document.getElementById (' i '). Contentwindow;

D.A ();

};

</script>

</body>

b page Code (http://example.com/b.html):

<script>

Document.domain = "example.com";

function A () {

Alert ("C");

}

</script>

<body>

</body>

Note: The Document.domain settings are limited, we can only set Document.domain to the parent domain of itself or higher, and the primary domain must be the same. For example: The document.domain of a document in www.org.example.com can be set to either www.org.example.com, org.example.com, or example.com, but cannot be set to Ftp.www.org.example.com, because this is a subdomain of the current domain and cannot be set to baidu.com because the primary domain is already different.

Note: The cross-domain of document.domain must be based on an HTML proxy linked to another HTML via an IFRAME, which is not feasible if it is directly accessed by Ajax.

Main Page code:

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

<title> cross-domain access to data </title>

<script type= "Text/javascript" >

function domaindata (URL, fn)

{

var IsFirst = true;

var iframe = document.createelement (' iframe ');

Iframe.style.display = ' None ';

var loadfn = function () {

if (IsFirst) {

iframe.contentWindow.location = ' http://a.com/null.html ';

Dynamically generate an IFrame loaded into page a.

IsFirst = false;

} else {

FN (iframe.contentWindow.name);

Iframe.contentWindow.document.write (");

Iframe.contentWindow.close ();

Document.body.removeChild (IFRAME);

IFRAME.SRC = ";

iframe = null;

}

};

iframe.src = URL;

if (iframe.attachevent) {

Iframe.attachevent (' onload ', LOADFN);

} else {

Iframe.onload = LOADFN;

}

Document.body.appendChild (IFRAME);

}

</script>

<body>

</body>

<script type= "Text/javascript" >

Domaindata (' http://b.com/data.html ', function (data) {

alert (data);

});

</script>

b page Code:

<script>

Window.name = ' data that needs to be passed across domains ';

</script>

4 , Window.name cross-domain scenarios.

The Name property of window exists in the lifetime of a window, that is, the interface loaded with window.location will share the Name property and will not be reset.

Therefore, we can pass the desired data through this name property.

Main Page code:

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

<title> cross-domain access to data </title>

<script type= "Text/javascript" >

function domaindata (URL, fn)

{

var IsFirst = true;

var iframe = document.createelement (' iframe ');

Iframe.style.display = ' None ';

var loadfn = function () {

if (IsFirst) {

iframe.contentWindow.location = ' http://a.com/null.html ';

Dynamically generate an IFrame loaded into page a.

IsFirst = false;

} else {

FN (iframe.contentWindow.name);

Iframe.contentWindow.document.write (");

Iframe.contentWindow.close ();

Document.body.removeChild (IFRAME);

IFRAME.SRC = ";

iframe = null;

}

};

iframe.src = URL;

if (iframe.attachevent) {//To determine if it is IE browser, because IE supports attachevent

Iframe.attachevent (' onload ', LOADFN);

} else {

Iframe.onload = LOADFN;

}

Document.body.appendChild (IFRAME);

}

</script>

<body>

</body>

<script type= "Text/javascript" >

Domaindata (' http://b.com/data.html ', function (data) {

alert (data);

});

</script>

b page Code:

<script>

Window.name = ' data that needs to be passed across domains ';

</script>

5 , HTML5 the Window.postmessage cross-domain scenarios.

A page code:

<script>

function OnLoad () {

var Iframe=document.getelementbyid (' iframe ');

var Win=iframe.contentwindow;

Win.postmessage ("Hello", *);//The first parameter is the message that needs to be passed, and the second is the field that receives the message, which can be a wildcard character.

}

</script>

b page Code:

<script>

Window.onmessage=function (e) {//register event to receive messages;

e=e| | event;//Get Time Object

alert (e.data);

}

</script>

6 , Cors cross-domain scenarios.

The wildcard "*" can be used when the server adds a cross-domain license for the response response header.

(Cross-domain requests can be either post or get-mode requests.) )

Service side:

Header ("access-control-allow-origin:http://www.a.com");

Client code:

$.ajax ("Www.cros.com/api/data", {

Type: "GET",

Xhrfields: {

Withcredentials:true

},

Crossdomain:true,

Success:function (data, status, XHR) {

}

});

This article is mainly for excerpt and collection.

Reference Documentation:

Http://www.cnblogs.com/oneword/archive/2012/12/03/2799443.html

Http://www.cnblogs.com/zjfree/archive/2011/02/24/1963591.html

http://narutolby.iteye.com/blog/1464436

Http://www.cnblogs.com/2050/p/3191744.html

JavaScript cross-domain Method learning Summary

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.