加載跨域的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);
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM