如何使用jQuery AJAX加载跨域HTML页面? [英] How can I load cross domain html page with jQuery AJAX?
问题描述
如何使用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 。
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?
推荐答案
我知道这是一个老帖子。但是,我希望这将有助于寻找同样的人。
只是你不能。 -origin policy or you need to set CORS headers for 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:
在服务器中创建端点以返回给定的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中的字符串的最简单方法 - 可以使用此方法创建 / getcontent
endpoint
Easiest way to read from a URL into a string in .NET - may use this to create /getcontent
endpoint
这篇关于如何使用jQuery AJAX加载跨域HTML页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!