JavaScript 跨域解决方案
1、主域与子域相互访问
主域名:www.demo.com
子域名:js.demo.com
在主域名下的页面添加一个 iframe ,并引入子域下的页面;
主域和子域的页面都要设置 document.domain = 'demo.com' 操持域名相同;
那么子域名下的 JavaScript 就可以像往常一样访问主域名了;
主域名下的页面:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>Ajax DEMO</title> </head> <body> <div id="msg"></div> <iframe src="http://js.demo.com/index.html"></iframe> <script type="text/javascript"> document.domain = 'demo.com'; </script> </body> </html>
子域名下的页:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>Site DEMO</title> </head> <body> <script type="text/javascript"> /** * 主域与子域相互访问 * 用iframe把此页面加到主域页面 * 两个页面都要设置 document.domain = 'demo.com' */ document.domain = 'demo.com'; var node = window.top.document.getElementById('msg'); var ajax = new XMLHttpRequest(); ajax.open('GET', 'http://js.demo.com/getJSON.php'); ajax.send(null); ajax.onreadystatechange = function(){ if(ajax.readyState == 4){ var json = decodeURIComponent(ajax.responseText); json = eval('(' + json + ')'); node.innerHTML = json.name; console.log(json); } } </script> </body> </html>
PHP 脚本:
<?php $arr = array('url' => 'http://www.qq.com', 'name' => '腾讯网'); // json encode $arr = json_encode($arr); echo $arr; ?>
2、JSONP
利用 script 标签 src 属性的可跨域性,去请求一个 PHP 页面并返回一段 JavaScript 脚本;
在主域上先定义好一个回调函数,再让请求返回执行这个回调函数;
主域名下的页面:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>JSONP DEMO</title> </head> <body> <div id="msg"></div> <script type="text/javascript"> function demo(){ var node = document.getElementById('msg'); node.innerHTML = 'JSONP'; } </script> <script src="http://js.demo.com/getJSONP.php" type="text/javascript"></script> </body> </html>
子域名下的页面:
<?php echo 'document.domain = "demo.com";demo();'; ?>
3、HTTP 与 HTTPS
由于 HTTP 与 HTTPS 使用不同的端口,所以浏览认为是跨域行为。
这种跨域的解决方法需要一个中间代理层,用同域下的一个服务器脚本去请求跨域的页面获取数据。
1、同域(HTTP)下的服务器脚本请求跨域(HTTPS)页面数据;
2、JavaScript 获取同域(HTTP)下的服务器脚本取得数据;
浙公网安备 33010602011771号