访问被拒绝。请求安全页面时出现JavaScript错误

时间:2011-02-03 15:14:24

标签: javascript ajax https xmlhttprequest

在页面SomePage.aspx上,通过JavaScript代码(XMLHttpRequest),我使用下一个代码调用SecuredPage.aspx

    var httpRequest = GetXmlHttp();
    var url = "https://myhost.com/SecuredPage.aspx";

    var params = "param1=" + document.getElementById('param1').value +
                "&param2=" + document.getElementById('param2').value;

    httpRequest.open("POST", url, true);
    httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    httpRequest.onreadystatechange = function() {
        //Call a function when the state changes.
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            alert(httpRequest.responseText);
        }
    }
    httpRequest.send(params); // HERE ACCESS IS DENIED.

    //---------------------------------------------
    function GetXmlHttp() {
        var xmlhttp = false;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        // Code for Internet Explorer.
        {
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (E) {
                    xmlhttp = false;
                }
            }
        }
        return xmlhttp;
    }

它会抛出访问被拒绝错误。如果发送到http(http://myhost.com/SecuredPage.aspx),它可以正常工作。

如何解决此问题?

3 个答案:

答案 0 :(得分:5)

如果您希望通过Ajax获取HTTPS页面,则需要从同一域上的HTTPS页面执行此操作,只要您使用Ajax,就没有其他办法。这是因为the same origin policy

也就是说,有很多方法可以不使用Ajax,for instance you can use frames

另一种方法是使用JSONP,但这需要你提取,好吧,JSON:)

第三种方式,对于生产网站而言往往不是很有用,但仍然可以很有趣,可以使用YQL作为代理。

最后,您始终可以设置自己的服务器端代理,以便调用获取HTTPS页面并将其发送的HTTP地址,但如果可以避免,这很少是一个很好的解决方案。

答案 1 :(得分:2)

这是因为浏览器将httphttps视为2个不同的网站/域,因此您必须遵守相同的原始政策。

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

解决这个问题的一种方法是使用jsonp。

答案 2 :(得分:1)

正如所说,您的问题是您的浏览器将此视为跨域请求。另一种方法是设置一个如下所示的crossdomain.xml文件:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="myhost.com" />
  <allow-access-from domain="ourhost.com" />
  <site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>

这个方法的专家,但我已成功使用它。可以通过添加更多allow-access-from标记来添加其他域。你可能需要做一些摆弄。 YMMV。