使用document.domain实现ajax跨子域

本文介绍了一种使用iframe代理方法解决AJAX跨子域问题的技术,包括在目标服务器上创建代理页面、引入jQuery、设置document.domain、发起跨域请求等步骤。

使用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/archive/2013/03/09/2951901.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值