可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
How can I load cross domain HTML page with 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 cannot load http://www.domain.com/path/filename. Origin null is not allowed by Access-Control-Allow-Origin.
we can't load cross domain page using AJAX because of the Same-origin policy.
I could try using 'jsonp' to bypass this restriction:
$.ajax({ type: "GET", url: url, dataType: "jsonp", success: function(data){ console.log(data); } });
But what if 'jsonp' is not supported in this site? this could be a problem.
What if I just want to read an external page and parse its HTML?
回答1:
I know this is an old post. But, I hope this will help someone else who is looking for the same.
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:
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); });
Easiest way to read from a URL into a string in .NET - may use this to create /getcontent
endpoint
回答2:
You can use 'AJAX Cross Origin' a jQuery plugin to load cross domain HTML page. AJAX Cross Origin is a jQuery plugin to allow Cross Origin AJAX requests. With this plugin we can easily bypass the Same-origin policy and do cross domain requests.
It is very simple to use:
$.ajax({ crossOrigin: true, url: url, success: function(data) { console.log(data); } });
You can read more about it here: http://www.ajax-cross-origin.com/