使用Jquery和IFrame的跨子域请求(GET,POST,...)

ben*_*che 5 subdomain ajax iframe jquery cross-domain

我正在尝试在我的主域(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>
Run Code Online (Sandbox Code Playgroud)

> 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>
Run Code Online (Sandbox Code Playgroud)

警报窗口始终包含Firefox 3.0/Chrome的" 302 "(重定向),IE8的" 0 "...虽然Firebug告诉我我的请求获得"200 Ok"状态(并且没有响应)...

我已经尝试过,直接在scripts.api.foo.com/iframe.html上,提出相同的请求,并获得相同的状态代码.

我非常沮丧,在网上徒劳地搜索实现跨子域的明确方法,或者对这些状态代码的解释......任何帮助都会受到欢迎.

非常感谢您的关注.再见.

bri*_*ong 5

不幸的是,跨域请求的规则也最终阻止了子域内的请求,即使技术上它是同一个服务器.您可以通过代理运行或使用跨域hack来允许$ .ajax调用运行.这里有一篇关于使用iFrame和跨域内容的非常好的文章

http://softwareas.com/cross-domain-communication-with-iframes

  • 好吧,我已经读过这篇文章,但是无法从他的理论中真正开发出一个解决方案......代理解决方案对我来说似乎很重要.对于那些尝试使用API​​开发服务的人来说,跨子域是一个常见的问题......对于如何解决这个问题,还没有达成共识? (4认同)