'How can I load cross domain html page with jQuery AJAX?
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?
Solution 1:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
