4

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?

Ninioe
  • 520
  • 1
  • 6
  • 6

2 Answers2

0

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

Community
  • 1
  • 1
Safeer Hussain
  • 1,230
  • 1
  • 15
  • 27
-3

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/

Ninioe
  • 520
  • 1
  • 6
  • 6