【问题标题】:Focus with Cross-domain Ajax in Opera专注于 Opera 中的跨域 Ajax
【发布时间】:2010-11-06 09:52:58
【问题描述】:

您需要 Opera 9.62 才能了解这一切是怎么回事……因为当我进行跨子域 JavaScript 调用(涉及 Ajax)时,这是唯一表现异常的浏览器。请考虑以下三个简单文件并将它们放置在适当的域中。

foo.html(boo.html iframe 的父级)foo.example.com

<!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>foo</title>
<script type='text/javascript'>

    document.domain = 'example.com';

    function sendRequest() {
        window.frames['boo'].sendRequest();
    }

</script> 
<head>
<body>

    <input type="submit" value="sendRequest" onclick="sendRequest();" />

    <iframe name="boo" src="http://boo.example.com/boo.html"></iframe>

</body>
</html>

boo.html(foo.html 的 iframe)boo.example.com

<!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>boo</title>
<script type='text/javascript'>

    document.domain = 'example.com';

    function sendRequest() {
        var request = null;

        if (window.XMLHttpRequest) { 
            request = new XMLHttpRequest(); 
        } else { 
            request = new ActiveXObject('Microsoft.XMLHTTP'); 
        }

        if (request) {
            request.open('GET', 'http://boo.example.com/helloworld.php', true); 

            request.onreadystatechange = function() {               
                if (request.readyState == 4) {
                    var result = request.responseText;

                    alert(result);
                }
            }

            request.send('');
        }
    }

</script> 
<head>
<body>
</body>
</html>

helloworld.phpboo.example.com

<?php
    echo 'Hello World!';
?>

如果您在 Opera 以外的浏览器中测试上述代码(在 v9.62 上测试),它就像一个魅力(我在 Safari、Firefox、Chrome 中测试过)。在 Opera 中,它不起作用,并且会抛出安全违规消息的错误。有人知道这是怎么回事吗? 我已经找到了问题的解决方案,稍后我会在这里发布(我也想看看你的解决方案),但我也想了解更多关于这个问题的信息- 谁能解释一下?

注意:我已经在自己的服务器上设置了所有文件,您可以查看here

更新:我刚刚在最新的 Opera 10.63 上进行了测试,它没有这样的问题。所以你肯定需要使用 Opera v9.62 来观察问题

【问题讨论】:

    标签: javascript ajax cross-domain opera


    【解决方案1】:

    一些较旧的 Opera 版本存在一个已知错误,该错误使设置 document.domain 会影响 XMLHttpRequest 的安全上下文。因此,在设置 document.domain 之后,脚本不再被允许从它实际来自的服务器加载内容。

    推荐的解决方案是简单地升级到不受该错误影响的版本,但是如果您绝对需要支持 9.6x,您可以轻松检测到异常并回退到使用 postMessage() 进行跨域通信。 (在这样的旧版本中,您需要调用 document.postMessage() - 在较新的版本中它是 window.postMessage() 但它是最初在文档中定义的 HTML5 规范的旧版本。)

    【讨论】:

      猜你喜欢
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      相关资源
      最近更新 更多