2011-02-03 87 views
1

安全的页面在页面SomePage.aspx,通过JavaScript代码(XMLHttpRequest的),我称之为SecuredPage.aspx使用下面的代码:访问被拒绝。 JavaScript错误的请求

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),它工作正常。

这怎么可能解决这个问题?

回答

5

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

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

另一种方法是使用JSONP,但这要求你取,好了,JSON :)

的第三种方式,那往往不生产网站是非常有用的,但仍然可以很有趣鼓捣与周围,是用YQL作为代理。

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

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。

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标签添加。你可能需要做一些摆弄。因人而异。

+1

我应该把/使用这个XML文件? – ihorko 2011-02-03 15:28:25