Use iframe to set proxy for cross-origin ajax requests

Source: Internet
Author: User

In today's project, remote data loading and page rendering are required, and ajax cross-origin requests are not realized until the development stage. So I want to use a proxy to solve this cross-origin problem.

What is cross-origin?

Simply put, for security reasons, JavaScript on the page cannot access data on other servers, that is, "same-origin policy ". Cross-origin means to bypass the same-origin policy restrictions in some ways to achieve communication between different servers.

Solution:Create a static proxy page on the server, call the proxy with iframe on the client, and request ajax through the document. getElementById ("proxy"). contentWindow object of iframe.

Server proxy page:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Strict // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Ajax cross-origin </title>
<Script src = "js/jquery-1.6.4.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
Document. domain = 'xxx. com ';
</Script>
</Head>
<Body>
</Body>
</Html>

Client ajax call code example:
Copy codeThe Code is as follows:
<Iframe src = "http://weixin.goumin.com/proxy.html" id = "proxy" style = "display: none;" onload = "loadDefaultData ();"> </iframe>
<Script type = "text/javascript">
Document. domain = "xxx.com ";
Function loadDefaultData (){
Var iframe_jquery = document. getElementById ("proxy"). contentWindow. $;
Iframe_jquery.ajax ({
Type: "POST ",
Url: "" + Math. random (),
Data :{},
Async: false,
DataType: 'json ',
Success: function (data ){
Alert (data );
}
});
}
</Script>

Url: "" + Math. random (),

Please pay attention to the red url line and use a random function to solve the browser cache problem. Make the URLs of each request different.

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.