Why cant I load an external resource from jQuery load method?

Jquery uses an ajax (XMLHttpRequest) request to load the data, but the browser allows this for resources on the same domain. (The answers above mention the Same origin policy). That's why it works with Temp.htm, but not www.google.com.

  • One way to get around this is to create a server script that will load the page for you - basically a proxy. Then you call

    $('#g').load("load.php?url=google.com")
    
  • The other solution is to use iframes for communication - I found this library, that seems to be what you need: jquery-crossframe

  • A third options is JSONP but that would not work it your case.

My opinion - go for the first option with a server-side proxy.


Why is there a same origin policy?

Imagine that you are checking some stuff on your ebay account. Then in another tab you open my site, where I have a script that makes a series of requests to ebay (you are still logged in) and bids you for an Audi A8 without you even noticing. Annoying... If it was your bank it can directly steal money from you.

The irony is that despite the same origin policy, the above attack is still possible.


You're not allowed to make cross-domain AJAX calls for security reasons - see Same Origin Policy.


This is due to security. You can read all about it along with a solution over at yahoo.


It's worth noting that you are not completely precluded from cross-domain requests in javascript.

As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSON-P callback and the URL that you call supports JSON-P output.

The following example is straight from the jQuery docs. It grabs the last four flickr pics tagged with "cat".

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
    function(data){
      $.each(data.items, function(i,item){
        $("<img/>").attr("src", item.media.m).appendTo("#images");
        if ( i == 3 ) return false;
      });
    });

You can read the docs here: http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback

Personally I use it to pull in my latest tweets on my blog without having to build it into my server-side code. That also has the added benefit of not having to write error handling code for the often spotty API service from Twitter. Just view source on my blog if you wanna see it: http://joreteg.com