在 http 页面上使用 https 的 Ajax

我的站点使用 http 和 https 协议; 它不影响内容。我的网站使用 jQuery ajax 调用,这也填充了页面上的一些区域。

现在,我想做所有的 Ajax 调用超过 https。(请不要问我为什么:) 当我在使用 https 协议的页面上时,Ajax 请求正在工作。 当我在使用 http 协议的页面上时,我得到一个 javascript 错误: 拒绝访问受限 URI

我知道这是一个跨域问题(事实上,这是一个跨协议问题) ,我知道我应该在 ajax 调用中使用与当前页面相同的协议。

不过,我希望所有 ajax 调用都是 https,并在通过 http 服务的页面上调用它们。 是否有任何解决方案来实现这一点(一些 json/代理解决方案?) ,还是根本不可能实现?

113759 次浏览

You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.

http://example.com/ may resolve to a different VirtualHost than https://example.com/ (which, as the Host header is not sent, responds to the default for that IP), so the two are treated as separate domains and thus subject to crossdomain JS restrictions.

JSON callbacks may let you avoid this.

Try JSONP.

most JS libraries make it just as easy as other AJAX calls, but internally use an iframe to do the query.

if you're not using JSON for your payload, then you'll have to roll your own mechanism around the iframe.

personally, i'd just redirect form the http:// page to the https:// one

Check out the opensource Forge project. It provides a JavaScript TLS implementation, along with some Flash to handle the actual cross-domain requests:

http://github.com/digitalbazaar/forge/blob/master/README

In short, Forge will enable you to make XmlHttpRequests from a web page loaded over http to an https site. You will need to provide a Flash cross-domain policy file via your server to enable the cross-domain requests. Check out the blog posts at the end of the README to get a more in-depth explanation for how it works.

However, I should mention that Forge is better suited for requests between two different https-domains. The reason is that there's a potential MiTM attack. If you load the JavaScript and Flash from a non-secure site it could be compromised. The most secure use is to load it from a secure site and then use it to access other sites (secure or otherwise).

Add the Access-Control-Allow-Origin header from the server

Access-Control-Allow-Origin: https://www.mysite.com

http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.