我正在尝试在我的主域名(http://foo.com)和我的API(http://api.foo.com)之间发展请求。
要绕过跨子域名的限制,我在主页(http ////foo.com/main.html)上使用iframe,指向iframe.html页面:scripts.api.foo .COM。
(scripts.api.foo.com和foo.com在同一台服务器上,api.foo.com在其他服务器上)
> iframe.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" xml:lang="en">
<head>
<title>Iframe</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.domain = 'foo.com';
function testIframe()
{
$.ajax({
url: "http://api.foo.com/utctime",
timeout: 7000,
complete: function(jqXHR, textStatus){
parent.alert(jqXHR.status);}
});
}
</script>
</body>
</html>
&gt; main.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" xml:lang="en">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.domain = 'foo.com';
function test()
{
pipeFrame.testIframe();
}
</script>
<iframe style="" src="http://scripts.api.foo.com/iframe.html" width="500" height="50" id="pipeFrame" name="pipeFrame"></iframe>
<form>
<p>
<input type="button" value="Hop" onclick="test();" />
</p>
</form>
</body>
</html>
警报窗口始终包含“ 302 ”(重定向)与Firefox 3.6 / Chrome,“ 0 ”与IE8 ...虽然Firebug告诉我我的请求得到了“200 Ok”状态(无响应)......
我已尝试直接在scripts.api.foo.com/iframe.html上提出相同的请求,并获得了相同的状态代码。
我非常沮丧,在网上徒劳无功地搜索实现跨子域的明确方法,或者对这些状态代码的解释...... 欢迎任何帮助。
非常感谢您的关注。 再见。
答案 0 :(得分:5)
不幸的是,跨域请求的规则也最终阻止了子域内的请求,即使技术上它是同一个服务器。您可以通过代理运行或使用跨域hack来允许$ .ajax调用运行。这里有一篇关于使用iFrame和跨域内容的非常好的文章
http://softwareas.com/cross-domain-communication-with-iframes
答案 1 :(得分:3)
如果您只定位现代浏览器(例如,IE 8),则可以实施OPTIONS请求。在尝试执行跨站点GET请求之前,现代浏览器将向目标(scripts.api.foo.com)发送OPTIONS请求,询问是否可以在源(foo.com)上使用其脚本。然后,Web服务器可以发送一个响应,其中说明,您可以在foo.com上使用我的脚本。
答案 2 :(得分:3)
jQuery ajax函数默认不起作用,IE等效于XHR CORS,称为XDR for XDomainRequest ... 只需在第一次ajax调用之前添加它,它可能适用于您的情况......
$(document).ready(function(e) {
// CORS + XDR for Internet Explorer
if ('XDomainRequest' in window&&window.XDomainRequest!==null)
{jQuery.ajaxSettings.xhr=function(){try{return new XDomainRequest();}
catch(e){}}; jQuery.support.cors = true;}
});
答案 3 :(得分:0)
把它扔到那里,但为什么不是JSONP?
{1, -2,-1})