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.