加载跨域的HTML页面AJAX

//下面是谷歌浏览器处理方式,微信端,直接使用微信链接不作处理,,火狐浏览器另行处理。。。

借鉴地址:http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-ajax

 //

//跨域请求处理----CORS Anywhere
$.ajaxPrefilter(function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});

var share_link = $scope.insurance.website;//微信文章地址
$.get(
share_link,
function (response) {
var html = response;
html = html.replace(/data-src/g, "src");
var html_src = 'data:text/html;charset=utf-8,' + html;
$("iframe").attr("src", html_src);
});

jQuery的阿贾克斯注意事项

  • 由于浏览器的安全限制,大多数的Ajax请求都受到了同样的原产地政策 ; 请求不能成功地从不同的域,子域,端口或协议检索数据。
  • 脚本和JSONP请求不受同源策略的限制。

有一些方法来克服跨域障碍:

有一些插件与帮助跨域请求:

小心!

克服这个问题的最好方法,就是通过在后台创建您自己的代理,这样,您的代理将指向其他域中的服务,因为在后端存在不的同源策略的限制。但是,如果你不能这样做,在后端,然后注意以下提示。


警告!

使用第三方代理不是一个安全的做法,因为他们可以跟踪你的数据,因此它可以用公共信息中使用,但从来没有与私人数据。


使用下面所示的代码示例jQuery.get()jQuery.getJSON() 都是速记方法jQuery.ajax()

CORS Anywhere

CORS Anywhere是一个Node.js的代理它增加了CORS标头的代理请求。
要使用API,只是前缀与API网址的URL。(支持HTTPS:见GitHub的库

如果你想在需要时自动启用跨域请求,使用下面的代码片段:

$.ajaxPrefilter( function (options) {
  if (options.crossDomain && jQuery.support.cors) {
    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
    //options.url = "http://cors.corsproxy.io/url=" + options.url;
  }
});

$.get(
    'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
    function (response) {
        console.log("> ", response);
        $("#viewer").html(response);
});
原文地址:https://www.cnblogs.com/yinweilong/p/6118690.html