Ajax cross-origin access-method Overview

Source: Internet
Author: User
Tags call back script tag

Case I. Web proxy method (on server)

 

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 solution can solve most of the Cross-origin access problems that can be considered at this stage, but requires website A to provide support for Web Proxy. Therefore, website a and website B must work closely together, in each interaction process, the server load of website a increases and the session status cannot be saved on behalf of users.

 

Case II. On-demand mode (on server)

 

Mymsn portal uses this method, but mymsn does not involve cross-origin access. Generate a new <SCRIPT> dynamically on the page and direct its src attribute to the website of another website. The content returned by this website must be a legal Javascript script, which is commonly used for JSON messages. This solution has the defect that the get method is adopted when the src attribute of the script completes the call. If the string passed during the request is too large, it may fail to run normally. However, this solution is very suitable for aggregation portals.

 

<HTML>
<Head>
<SCRIPT>
Function loadcontent ()
{
VaR S = Document. createelement ('script ');
S. src = 'HTTP: // www.anotherdomain.com/testcrossjs.aspx? F = setdivcontent ';
Document. Body. appendchild (s );
}

Function setdivcontent (V)
{
VaR DV = Document. getelementbyid ("DV ");
DV. innerhtml = V;
}
</SCRIPT>
</Head>
<Body>
<Div> </div>

<Input value = "Click me">
</Body>
</Html>

Here is www.anotherdomain.com/testcrossjs.aspx,

<SCRIPT runat = "server">
Void page_load (Object sender, eventargs E)
{
String F = request. querystring ["F"];
Response. Clear ();
Response. contenttype = "application/X-JavaScript ";
Response. Write (string. Format (@"
{0} ('{1 }');",
F,
Datetime. Now ));
Response. End ();
}
</SCRIPT>

Click the "Click me" button to generate a new script tag, download the corresponding Javascript script, and call back setdivcontent () to update the content of a div on the webpage.

 

 

Case III. IFRAME method (on server)

 

After checking a post about cross-origin access on javaeye, he mentioned that he has used IFRAME to solve cross-origin access problems. The IFRAME method can be used to submit and obtain data. However, because the parent window cannot interact with the Child Window (in the case of cross-origin access, this interaction is denied ), therefore, the effect on the parent window cannot be completed.

Embedded on the page or dynamically generate An iframe pointing to another website. Then, the two webpages can transmit messages by changing the anchor hash fragment of the other website. Changing the anchor hash fragment of a Web page does not allow the browser to reload the web page, so the status of a Web page is maintained, and the web page itself can use a timer (timer) to detect the changes in your anchor hash and change your status accordingly.

 

1. http: // domain1/testcross.html:

<HTML>
<Head>
<SCRIPT>
VaR url = "http: // domain2/testcross.html"
VaR oldhash = NULL;
VaR timer = NULL;

Function gethash ()
{
VaR hash = Window. Location. Hash;
If (hash. length> = 1) & (hash. charat (0) = '#'))
{
Hash = hash. substring (1 );
}

Return hash;
}
Function sendrequest ()
{
VaR d = document;
VaR T = D. getelementbyid ('request ');
VaR F = D. getelementbyid ('alienframework ');
F. src = URL + "#" + T. Value + "<br/>" + new date ();
}

Function setdivhtml (V)
{
VaR d = document;
VaR DV = D. getelementbyid ('response ');
DV. innerhtml = V;
}

Function idle ()
{
VaR newhash = gethash ();

If (newhash! = Oldhash)
{
Setdivhtml (newhash );
Oldhash = newhash;
}

Timer = Window. setTimeout (idle, 100 );
}

Function window. onload ()
{
Timer = Window. setTimeout (idle, 100 );
}
</SCRIPT>
</Head>
<Body>

Request: <input> <input value = "send"/> <br/>
Reply: <div> </div>

<IFRAME src = "http: // domain2/testcross.html"> </iframe>

</Body>
</Html>

2. http: // domain2/testcross.html:

<HTML>
<Head>
<SCRIPT>
VaR url = "http: // domain1/testcross.html"
VaR oldhash = NULL;
VaR timer = NULL;

Function gethash ()
{
VaR hash = Window. Location. Hash;
If (hash. length> = 1) & (hash. charat (0) = '#'))
{
Hash = hash. substring (1 );
}

Return hash;
}
Function sendrequest ()
{
VaR d = document;
VaR T = D. getelementbyid ('request ');
VaR F = parent;
// Alert(f.doc ument); // try to remove this comment and you will get "access is denied"
F. Location. href = URL + "#" + T. Value + "<br/>" + new date ();
}

Function setdivhtml (V)
{
VaR d = document;
VaR DV = D. getelementbyid ('response ');
DV. innerhtml = V;
}

Function idle ()
{
VaR newhash = gethash ();

If (newhash! = Oldhash)
{
Setdivhtml (newhash );
Oldhash = newhash;
}

Timer = Window. setTimeout (idle, 100 );
}

Function window. onload ()
{
Timer = Window. setTimeout (idle, 100 );
}
</SCRIPT>
</Head>
<Body>

Request: <input> <input value = "send"/> <br/>
Reply: <div> </div>

</Body>
</Html>

The two web pages are basically the same. The first web page is embedded with an IFRAME. After you click "send", the content in the text box is transmitted to IFRAME through hash fragment. After you click "send" in IFRAME, it will pass the content in the text box to the parent window through hash fragment. Because only hash fragment is modified, the browser does not load the webpage content again. Here, a timer is used to detect URL changes. If it changes, the content of one of the divs is updated.

 

Case IV. User Local dump mode (local)

 

The feature that IE is attached to the Windows platform provides us with an IFRAME-based solution that uses memory to bypass, that is, data can be transmitted between two windows Windows through the windows clipboard on the client. You only need to set interval on the receiving side for polling. After obtaining the result, you can clear interval. The platform independence of FF determines that it does not support the clipboard method. In the previous versions of FF, the plug-in vulnerability has been fixed, so FF cannot complete the dark Data Warehouse through memory. Because the file operation FF does not provide support (data transmission cannot be completed through cookie cross-origin), this technical method can only be used in IE.

 

 

Case V: (in fact, server a uses IFRAME to solve the problem of communication with server B)

 

The problem to be solved occurs when the user submits a webpage URL (including tag and notes) to the bookmark server.

There are at least three methods for URL submission:

1. log on to the submit page of the bookmark server and submit the favorite URL to the server through this page.

2. Install the browser plug-in and submit the URL to the server through the plug-in.

3. dynamically load the Javascript tool from the bookmark server to the current page and use it to complete the submission.

 

The first method is the easiest to develop, but it is troublesome for users. You need to log on to the bookmark server each time before submission. The second method is not familiar with plug-in development, in addition, users do not like too many plug-ins to fill their browsers. The third method is less difficult to develop and avoids the trouble of logging on to the server every time, So they finally use it. In the third method, the Javascript gadgets dynamically load not only need to generate the UI for users to fill in information (URL, Tag, notes, etc.), when users click to submit, it also needs to complete the function of communicating with the server.

Cross-origin access is simply the Javascript of website.CodeAttempt to access website B, including submitted content and obtained content. For security reasons, cross-origin access is disabled by various browsers by default. I believe all my friends who have written cross-origin access to Ajax have been notified of "no permission. An error occurred while sending data to the bookmark server through XMLHTTP. As a result, I started to use JavaScript gadgets to dynamically create a hidden IFRAME on the user's webpage. The SRC of IFRAME points to a servlet on the server, it tries to call the Javascript provided in IFRAME to communicate with the server. But unfortunately,TheJavaScript code access to IFRAME is also classified by the browser as cross-origin access (specifically, the SRC of IFRAMEPoint to other websites), Failed again.

In the endArticleDifferent from IFRAME, if website a loads JavaScript from website B, website a can freely access the javascript content without being considered as cross-origin access by the browser.Imitating IFRAME idea. When you click Submit, You can dynamically create a JavaScript Object whose SRC points to a servlet on the bookmark server. Note: URL, Tag, notes, user, password, and other information are used as SRC URLs.Parameters are passed to the server.See the following code:

var url = "http: // localhost: 8080/deeryard/bookmarkservlet? "+

" url = "+ url_source +" & "+" Title = "+ title +" & "+

"tag =" + tag + "&" + "Notes =" + notes + "&" + "user =" + User + "&" + "Password =" + password;

url = encodeuri (URL );

// submit to server with a trick

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

js_obj.type = "text/JavaScript ";

js_obj.setattribute ("src", URL );

// get response from server by appending it to document

document. body. appendchild (js_obj);

 

In the preceding example, js_obj.setarrribute () submits the information to the bookmark Servlet as the src url parameter. How can users obtain the server response information? The answer is the last line of code. The servlet output must be JavaScript code. It can call other JavaScript Functions on the user's webpage and operate on DOM objects. The following servlet code generates a JavaScript function call:

Out. Write ("onserverresponse (inadequate_information );");

After document. Body. appendchild (js_obj) is executed, onserverresponse (inadequate_information) will be executed to make the client webpage respond to the server results. This complete communication process is complete.

 

Casevi: Tomcat + PHP + HTML (including JS) (on server)

 

Tomcat has been installed on server a. Let's write a test.html (including JS) file and a PHP file (which meets the cross-origin communication requirements ).

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.