Summary of JavaScript cross-origin and Ajax cross-origin Solutions

Source: Internet
Author: User
Tags in domain subdomain domian

In a recent project, Ajax cross-Origin data retrieval is required. If it is true that there is no problem in the current domain, a prompt box is displayed in the browser of the second-level domain and other domains: "This page is accessing data out of its control scope. This is dangerous. Continue"

1. What causes cross-origin failure of Ajax?
Ajax itself uses the XMLHTTPRequest object to interact with data. For security reasons, the browser does not allow cross-origin operations of JavaScript code, so it will warn you.

2. Is there any perfect solution?
No. There are many solutions, but they can only be selected based on your actual situation.

Specific situations include:
1. Mutual access between the domain and subdomain: www.aa.com and book.aa.com
2. Mutual access between the domain and other domains: IFRAME for www.aa.com and www.bb.com
3. Mutual access between the domain and other domains: Use XMLHttpRequest as the access proxy for www.aa.com and www.bb.com
4. Mutual access between the domain and other domains: www.aa.com and www.bb.com use js to create dynamic scripts

SolutionMethod:
1. If you want to achieve data interaction, you must develop www.aa.com and book.aa.com. You can use IFRAME to add book.aa.com
Add document. Domain = to both www.aa.com and IFRAME on a page of www.aa.com.
"Aa.com" to unify the domain and implement cross-origin access. Just like the built-in IFRAME in the same domain, you can directly call the Js in it. (I did not try this method.
Try, but theoretically feasible)

2. When the two domains are different and you want to call each other, you also need to develop the two domains. IFRAME can be used to call data. The solution is to use
The hash attribute of the window. Location object. The hash attribute is http: // domian/web/a.htm # dshakjdhsjka
# Dshakjdhsjka. Using js to change the hash value does not refresh the web page. In this way, you can use js to access the hash value for communication. However, most
As long as the browser changes the hash, it will record the history. You need to handle it before and after it is very troublesome. But it can still be used for simple processing. I will download the specific code below. The general process is
Page A and page B are in different domains, B is added to a through IFRAME, A modifies the hash value of IFRAME through JS, and B is used as a listener (because JS can only modify the hash, Data
Whether the hash value of B is changed can only be determined by B). It is detected that the hash value of B is modified to get the modified value. After processing, the value required by a is returned, modify the hash value of.
For example, http: // domian/web/a. aspx? Id = 3. In B, the direct parent. Window. Location is none.
If a does not have the permission to retrieve the data, a must upload the data, which is troublesome.) Similarly, a must listen to the data, if the hash changes, the returned data is obtained and the corresponding
Processing.

3. This situation is the most common and most commonly used. Www.aa.com and www.bb.com, you can only modify one, that is, the other is others'. People tell you
To obtain the data, you can access the format of the XX connection parameter and finally return the data. What you need to do is to create a webpage in your domain so that the server can obtain data from other websites and then return the data.
Back to you. In domain1, A requests data to getdata. aspx in the same domain, and getdata. aspx requests data
Responsedata. aspx sends a request, and responsedata. aspx returns data to getdata. aspx,
Getdata. aspx is returned to a, which completes a data request. Getdata. aspx acts as a proxy. For more information, see my code.

4. the difference between this and the previous one is that the request uses the <SCRIPT> tag for the request. This requirement is also required by you to develop both domains. The principle is JS file injection.
A
Generate a JS tag. Its SRC points to a page B in another domain of the request, and B returns data, which can directly return the JS Code. Because the src attribute of the script can be cross-Origin
. The Code is also relatively simple.

Summary:
First case: domain and subdomain issues can completely resolve interactions.
Case 2: Cross-origin is difficult to implement and requires control from both domain developers. It is suitable for simple interaction.
Case 3: Cross-origin: developers only need to control one domain. It is a common method to add a proxy to obtain data.
Case 4: Cross-origin, both domain developers need to control and return a piece of JS Code.

==============================

Text Box on the hosts page.

Note:
B .html is an HTML webpage and cannot receive the post value from other websites. Therefore, you cannot directly post the value. However, if the received page is B. aspx or
B. asp
But can I directly post it? The answer is yes, but B. asp or B. aspx must be refreshed before it can dynamically change the elements or values of the receiving page without refreshing.
What about it? (The local project of IE can implement cross-origin access, but cross-origin access to the Internet is denied by default. Cross-Domain access to Firefox local projects and the Internet is rejected .)

Principle:

The browser prohibits cross-Origin data access, but the browser does not prohibit cross-Origin Cross-framework post value transfer. We can post data to a page in Domain B in the framework of Domain A, and then implement data access in the domain through the framework page of Domain B. This is actually a small trick in HTML applications, and does not use other advanced knowledge to implement cross-Origin data submission.

Method:

Add two pages in the B domain to implement cross-Origin data access, post. aspx and Main. aspx.

Sums and (frmpost) post. aspx.

A.html of the a domain:

<Form action = "http://www. B **. com/post. aspx" method = "Post" target = "frmpost">

<Input id = "cmd" type = "text" size = "20">

<Input type = "Submit">

</Form>

<IFRAME src = "http://www. B **. com/Main. aspx"> </iframe>

Main. aspx of Domain B:

<Frameset rows = "*, 0" frameborder = "no" border = "0" framespacing = "0">

<Frame src = "B .html" name = "frmmain">

<Frame src = "post. aspx" name = "frmpost">

</Frameset>

 

We first save the data to B to form in a.html, and then post it to post. aspx in B.

At this time, post.aspxreceives the value, and then implements the parent framework of the domain, namely, B .html.

String cmd = request. Form ["cmd"];

If (null! = Cmd & string. Empty! = Cmd)

{


Response. Write ("<script language =/" javascript/"for =/" window /"
Event =/"onLoad/"> If (parent & parent. Frames [/"frmmain/"])
{Control the Execution Code of B .html here} </SCRIPT> ");

}

It is not difficult to find that the cross-frame (that is, a frame exceeded in the middle) method is used to achieve cross-Origin data access. That is, post to the sub-frame of the frame.

Postscript:

This example is just a solution for cross-origin access under some special circumstances, and may be helpful to you. Because the method is simple, the application has many limitations. (However, I think this is very like Ajax. The page is not refreshed, and the data processing on the server is also completed ^ o ^ ).

Related documents:

Cross-origin access solution for Web Applications

Anyone who has worked on AJAX development across multiple websites knows that if we want to use Ajax on website a to obtain specific content on website B, if website a and website B are not in the same domain, a cross-origin access problem occurs. Cross-origin access of AJAX is a common problem for existing Ajax developers.

For cross-origin access, IE prompts a warning box to remind you. If a user adds the website to a trusted website or lowers the security level, ie will not remind you of this issue.

If Firefox or other non-Microsoft browsers encounter cross-origin access, the solution is to reject access.

Yes
People say that IE is a mainstream browser, as long as it can be used normally. Although Ie can handle this problem, there is a premise that you can either click yes after the warning box is displayed on the page (Click No
Do not execute the Ajax call), or the user will include the website into a trusted site. These two methods are common in the application of enterprise management systems, because the system administrator can use administrative measures to ensure that users
. However, this approach does not work for website or portal development on the Internet.

I recently encountered this problem. I need to finish some special effects on the main window after cross-origin access, search for some materials, and perform compatibility tests in different browsers, several feasible solutions are found:

1,
Web proxy method. That is, the cross-origin access requests to website B generated when you access website a are submitted to the specified page of website a. The page replaces the user page to complete interaction and return appropriate results. This
The solution can solve most of the Cross-origin access problems that can be considered at this stage. However, website a must provide Web Proxy Support. Therefore, website a and website B must work closely together, in each interaction process, website
Server load increases, and session status cannot be saved on behalf of users.

2. On-demand mode. Mymsn portal is used
However, mymsn does not involve cross-origin access. Dynamically control the generation of SCRIPT tags. You can call cross-origin pages by modifying the src attribute of SCRIPT tags. This solution
The drawback is that the src attribute of the script completes the get method when the call is completed. If the string passed during the request is too large, it may fail to run normally. However, this solution is very suitable for gathering
Portal.

3. IFRAME mode. I checked a post about cross-origin access that woke up on javaeye. He mentioned that he has
The problem of Cross-origin access is solved using IFRAME. The IFRAME method can be used to submit and obtain data, but the parent window and Child Window cannot interact (cross-origin access
), So the effect on the parent window effect cannot be completed.

(I found this article, add address: http://www.javaeye.com/topic/15641)

4,
Local user dump mode: the feature that IE is attached to the Windows platform provides us with an IFRAME-based solution that uses memory to bypass, that is, the two windows
The client transmits data through the windows clipboard. You only need to set interval on the receiving side to perform round-robin. After obtaining the result, clear interval. FF's
Platform independence determines that it does not support clipboard. In the past, the Plugin Vulnerability in FF was fixed, so FF cannot complete the dark Data Warehouse through memory. Because file operations FF
It does not provide support (data transmission cannot be completed through cookie cross-origin), so this technical method can only be used in IE.

5. Self
Methods used to solve this problem: in combination with the previous methods, when accessing website a, request website B to complete data processing, and then obtain the desired results based on the returned ID. The disadvantages of this method are also very clear.
The load on website B is increased. The session is also maintained, and the interaction between website a and website B is enhanced. Most importantly, this solution satisfies all my needs.

To sum up, I recommend the on-demand method when you can select the above scheme. This method can solve most of your problems without submitting a large amount of data.

 

====================================

Site: http://www.somedomain.com

Destination: http://bbs.somedomain.com

Solution:

1. In the target site document. Domain = 'somedomain. com ';

Create an ajax.html file and reference the Ajax method (we call it a service intermediary)

Then create an Ajax object var webreq = new Ajax ();

2. log on to the local site for document. Domain = 'somedomain. com ';

Use iframeto reference the ajax.html of the target site.

 

Detailed method:

1. One page of the website (test.html)

HTML:

<HTML>

<Head>

<SCRIPT type = 'text/JavaScript '> document. Domain = 'somedomain. com'; </SCRIPT>

<SCRIPT type = 'text/JavaScript '>

Function getajax ()

{

VaR SPN = Document. getelementbyid ('pninfo ');

VaR bbswin = Document. getelementbyid ('ifrwindow'). contentWindow;

VaR Ajax = bbswin. webreq;

Ajax. config. Result = 'testajaxcross ';

Ajax. config. returntype = 'content ';

Ajax. actionpost ('HTTP: // bbs.somedomain.com/doajax.aspx', SP );

}

</SCRIPT>

</Head>

<Body>

<Span id = 'pninfo'/>

<Input type = 'button 'Id = 'ajaxbtn' onclick = 'getajax 'value = 'get'/>

</Body>

<IFRAME id = 'ifrwindow' src = 'HTTP: // bbs.somedomain.com/ajax.html' style = 'display: none; '> </iframe>

</Html>

 

//////////////////////////////////////// /////////////////////////////////////

 

2. ajax.html of the target site

HTML:

<HTML>

<Head>

<SCRIPT type = 'text/JavaScript '> document. Domain = 'somedomain. com'; </SCRIPT>

<SCRIPT type = 'text/JavaScript 'scr = 'HTTP: // bbs.somedomain.com/ajaxmethod.js'> </SCRIPT>

<SCRIPT type = 'text/JavaScript '> var webreq = new Ajax (); </SCRIPT>

</Head>

<Body>

</Body>

</Html>

 

----------------------------------------------------------------

Target Site: doajax. aspx

HTML is empty

Doajax. aspx. CS

Code (page_load)

Response. Write ("<zwd> <content> have you seen the effect? </Content> </zwd> ");

Return;

 

========================================================== ==================

 

Ajaxmethod. JS Code

 

/// // Ajax // class ////// /////////////
// Power by gloot copyright @ 2006
// Edit section

// Blog http://blog.sina.com.cn/tecz
// QQ 345268267
//////////////////////////////////////// ///////////////////

VaR try = {
These: function (){
VaR returnvalue;
For (VAR I = 0; I <arguments. length; I ++ ){
VaR Lambda = arguments [I];
Try {
Returnvalue = Lambda ();
Break;
} Catch (e ){}
}
// Alert (123 );
Return returnvalue;
}
}

Function grr (RP ){
If (Regexp. $1)/(. *)/. Exec ("");
VaR Re = new Regexp ("<result> (. *) <// result> ");
Re.exe C (RP );
If (Regexp. $1) return Regexp. $1;
Return "";
}

Function CRR (RP ){
If (Regexp. $1)/(. *)/. Exec ("");
VaR Re = new Regexp ("<content> (. *) </content> ");
Re.exe C (RP );
If (Regexp. $1) return Regexp. $1;
Return "";
}

VaR Ajax = function (){}
// Var xhr; this definition does not work.
Ajax. Prototype. init = function (){
Return try. These (
Function () {return New activexobject ("msxml2.xmlhttp ")},
Function () {return New activexobject ("Microsoft. XMLHTTP ")},
Function () {return New XMLHttpRequest ()}
) | False;
}

Ajax. Prototype. Config = {
Result :"",
Sucinfo :"",
Faildinfo :"",
URL :"",
Returntype: "Compare", // enter compare to compare whether the returned characters are consistent. You must specify the result value. // other returned content
Execfunc: function (TY ){
If (typeof execresult = 'function ')
Execresult (TY );
},
Senddata :""
}

VaR AJ = new Ajax ();

Ajax. Prototype. Action = function (URL) {// synchronous
Url = URL + '& E =' + math. Random ();
VaR xhr = AJ. INIT ();
Xhr. onreadystatechange = function ()
{
If (xhr. readystate = 4)
{
If (xhr. Status = 200)
{
AJ. funcresult (AJ. config. SPN, xhr );
}
}
}
Xhr. Open ("Post", URL, false );
Xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");

Xhr. Send (null );

}

Ajax. Prototype. actionfor = function (URL, SPN) {// asynchronous

Url = URL + '& E =' + math. Random ();
VaR xhr = AJ. INIT (); // This write is for multi-asynchronous execution

Xhr. onreadystatechange = function ()
{
If (xhr. readystate = 4)
{
If (xhr. Status = 200)
{
AJ. funcresult (SPN, xhr );
}
}
}
Xhr. Open ("get", URL, true );

Xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
Xhr. Send (null );
}

Ajax. Prototype. actionalert = function (URL) // execute the synchronization in the alert prompt box
{
Url = URL + '& E =' + math. Random ();
VaR xhr = AJ. INIT (); // This write is for multi-asynchronous execution

Xhr. onreadystatechange = function ()
{
If (xhr. readystate = 4)
{
If (xhr. Status = 200)
{
AJ. alertresult (xhr );
}
}
}
Xhr. Open ("get", URL, false );

Xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
Xhr. Send (null );
}

Ajax. Prototype. actionpost = function (URL, SPN) // send synchronously
{
Url = URL + '? E = '+ math. Random ();
VaR xhr = AJ. INIT (); // This write is for multi-asynchronous execution

Xhr. onreadystatechange = function ()
{
If (xhr. readystate = 4)
{
If (xhr. Status = 200)
{
AJ. postresult (SPN, xhr );
}
}
}

Try {
If (Netscape. Security. privilegemanager. enableprivilege)
{
Netscape. Security. privilegemanager. enableprivilege ('universalbrowserread ');
Netscape. Security. privilegemanager. enableprivilege ("universalxpconnect ");
}
} Catch (e ){};

Xhr. Open ("Post", URL, true );

Xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
// Xhr. setRequestHeader ("Content-Length", pars. Length );
Xhr. setRequestHeader ("connection", "open ");
Xhr. Send (webreq. config. senddata );
}

Ajax. Prototype. getjsondata = function (URL, SPN)
{
Url = URL + '? E = '+ math. Random ();
VaR xhr = AJ. INIT (); // This write is for multi-asynchronous execution

Xhr. onreadystatechange = function ()
{
If (xhr. readystate = 4)
{
If (xhr. Status = 200)
{
AJ. jsonresult (SPN, xhr );
}
}
}

Xhr. Open ("Post", URL, true );

Xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
// Xhr. setRequestHeader ("Content-Length", pars. Length );
Xhr. setRequestHeader ("connection", "open ");

Xhr. Send (null );
}

Ajax. Prototype. onresult = function (v ){
Return v = AJ. config. result;
}

Ajax. Prototype. funcresult = function (SPN, xhr)
{// Alert (SPN. ID );

If (AJ. config. returntype = 'compare ')
{
If (AJ. onresult (GRR (xhr. responsetext )))
{

SPNs. innerhtml = AJ. config. sucinfo;
AJ. config. execfunc (AJ. config. Result );
If (AJ. config. url! = '')
{
Window. Location. href = AJ. config. url;
}
}
Else
{

SPNs. innerhtml = AJ. config. faildinfo;

}
}
Else
{
SPNs. innerhtml = CRR (xhr. responsetext );
AJ. config. execfunc (AJ. config. Result );
}

}

Ajax. Prototype. alertresult = function (xhr)
{
If (AJ. config. returntype = 'compare ')
{
If (AJ. onresult (GRR (xhr. responsetext )))
{
Alert (AJ. config. sucinfo );
AJ. config. execfunc (AJ. config. Result );
}
Else
{
Alert (AJ. config. faildinfo );
}
}
Else
{
Alert (CRR (xhr. responsetext ));
AJ. config. execfunc (AJ. config. Result );
}
}

Ajax. Prototype. postresult = function (SPN, xhr)
{
If (AJ. config. returntype = 'compare ')
{
If (AJ. onresult (GRR (xhr. responsetext )))
{
SPNs. innerhtml = AJ. config. sucinfo;
AJ. config. execfunc (AJ. config. Result );
}
Else
{
SPNs. innerhtml = AJ. config. faildinfo;
}
}
Else
{
SPNs. innerhtml = CRR (xhr. responsetext );
AJ. config. execfunc (AJ. config. Result );
}
}

Ajax. Prototype. jsonresult = function (SPN, xhr)
{
VaR jsonstr = xhr. responsetext;
VaR JSON = eval ("return" + jsonstr );

// Get data JSON. Something JSON: {Username: "123", content :""};

AJ. config. execfunc (AJ. config. Result );
}
//////////////////////////////////////// ///////////////////////

VaR WebServices = function (){}
WebServices. Config = {

}

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.