使用document.domain实现ajax跨子域

使用document.domain实现ajax跨子域

跨子域:比如static.xxx.oooo.com的页面使用ajax方式调用xxx.oooo.com的接口的时候,会出现跨域的错误。最开始以为在static.xxx.oooo.com的页面设置domian为xxx.oooo.com的时候就会解决问题,但是发现问题依然存在。

上网一查,还蛮多资料,特别是随网之舞的blog里介绍用document.domain解决跨子域的方法。http://dancewithnet.com/2007/07/22/solve-cross-sub-domain-ajax-with-document-domain/

就是使用iframe设置代理的方式。

按部就班:

1、  在被访问的服务器(xxx.oooo.com)里新建一个代理页面,比如proxy.html

里面的代码:

<!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>用document.domain解决Ajax跨域</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js" type="text/javascript"></script>

<script type="text/javascript">//<![CDATA[

         document.domain = 'xxx.oooo.com';

//]]></script>

<Script language="javascript">

</Script>

</head>

<body></body>

</html>

里面引入了jquery,不然后续不能使用jquery的方法呀。

2、  在调用页面里先引入这个iframe

<iframe src="http://xxx.oooo.com/promote/promote_proxy.html" id="proxy"></iframe>

3、  发起调用的时候获取这个iframe,并用iframe里的ajax方式实现请求

var iframe=document.getElementById('proxy').contentWindow; 

iframe.window.jQuery.ajax({

         url:"http://xxx.oooo.com/php/index.php?d=active&c=active&m=index",

data:"promoteId="+promoteId+"&activeId="+this.getAttribute("data")+"&msg="+encodeURIComponent("{"+global.info.msg.join(",")+"}"),

         method:"post",

         dataType:"",

         success:function(data){

                  

         },

         error:function(data){

                   alert(123);

         }

});

4、完毕

原文地址:https://www.cnblogs.com/fredshare/p/2951901.html