0

I'm having some issues when trying to call in content from a subdomain using .load

After googling and reading and not really understanding I don't think this can be done?

Here's the error I'm receiving:

XMLHttpRequest cannot load http://content.domain.co.uk/test.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.co.uk' is therefore not allowed access.

I've read somewhere that I can add the document.domain into my external file - This also doesn't work - Am I doing this right?! I'm not sure.

<script type="text/javascript">
            document.domain = 'domain.co.uk';
</script>

Here is my code:

$(function() {
    $('#activate').click( function() {
        $('#activate').hide();
        $('#loadingImg').show();
        $('#testContainer').load('http://content.domain.co.uk/test.html #main', function() {
            $('#loadingImg').hide();
       });
   });
});

I've read that what I'm trying to do could probably be achieved using JSON - However, I'm really not sure what or how to do this. Any help would be really appreciated.

Thanks!

Nick
  • 2,261
  • 5
  • 33
  • 65
  • some answers here http://stackoverflow.com/questions/25707287/how-can-i-load-cross-domain-html-page-with-jquery-ajax – Luca Rasconi Dec 05 '14 at 15:43

1 Answers1

0

You need to provide a Access-Control-Allow-Origin header for this to work. Since you are accessing a .html file this will have to be done through the web server. If you are using Apache this is how to do it: http://enable-cors.org/server_apache.html

If the subdomain is under your control you can wrap the html file using some scripting language, for example PHP:

<?php
  header("Content-type: text/plain; charset=utf8");
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

  echo file_get_contents("file.html");
?>

The alternative is to use JSONP: http://en.wikipedia.org/wiki/JSONP

Jesper We
  • 5,977
  • 2
  • 26
  • 40