問題描述
如何使用 jQuery AJAX 加載跨域 HTML 頁面?
How can I load cross domain HTML page with jQuery AJAX?
假設我想使用 jQuery AJAX 在我的域之外獲取一個頁面:
Suppose I want to get a page outside my domain using jQuery AJAX:
$.get('http://www.domain.com/mypage.html', function(data) {
alert(data);
});
我可能會收到此錯誤消息:
I will probably get this error message:
XMLHttpRequest 無法加載 http://www.domain.com/path/filename.起源Access-Control-Allow-Origin 不允許 null.
XMLHttpRequest cannot load http://www.domain.com/path/filename. Origin null is not allowed by Access-Control-Allow-Origin.
由于 同源策略,我們無法使用 AJAX 加載跨域頁面.
we can't load cross domain page using AJAX because of the Same-origin policy.
我可以嘗試使用 'jsonp' 來繞過這個限制:
I could try using 'jsonp' to bypass this restriction:
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
但是如果這個站點不支持jsonp"怎么辦?這可能是個問題.
But what if 'jsonp' is not supported in this site? this could be a problem.
如果我只想讀取外部頁面并解析其 HTML 怎么辦?
What if I just want to read an external page and parse its HTML?
推薦答案
我知道這是一個舊帖子.但是,我希望這會幫助其他正在尋找相同的人.
只是你不能. - 同源策略或者你需要為 www.domain.com
Simply you can't. - same-origin policy or you need to set CORS headers for www.domain.com
但是,如果您只想將外部頁面內容提取到您的頁面,您可以使用一種解決方法:
But, If you just want to fetch an external page content to your page, there is a workaround you could do:
在您的服務器中創建一個端點以返回給定外部 URL 的 HTML 內容.(因為您無法將外部內容獲取到瀏覽器 - 同源策略)
Create an endpoint in your server to return the HTML content for the given external URL. (because you can't get external content to the browser - same-origin policy)
JS:
var encodedUrl = encodeURIComponent('http://www.domain.com/mypage.html');
$.get('http://www.yourdomain.com/getcontent?url=' + encodedUrl, function(data) {
console.log(data);
});
在 .NET 中從 URL 讀取到字符串的最簡單方法 - 可以使用這個創建 /getcontent
端點
這篇關于如何使用 jQuery AJAX 加載跨域 html 頁面?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!