Maurits Rijk
Maurits Rijk

Reputation: 9985

Loading json fails from url, works from file

I have the following code snippet:

    $.getJSON("http://localhost:8080/images",
  function(data) {

    var items = [];

    $.each(data, function(key, val){
        items.push('<li id="' + key + '">' + val + '</li>');
    });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');

  });

The url returns json that looks like {"count" : 0}. When I try to load the page in my browser the .getJSON call fails. However when I save the result from "http://localhost:8080/images" to a file and try to load it with the same Javascript (url replaced by file name) everything works as expected and I get a list.

Any pointers?

Upvotes: 0

Views: 289

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075467

You're probably running into the Same Origin Policy. In the normal course of things, you can only use "ajax" (that is, a genuine XMLHttpRequest call) to retrieve resources from the same origin as the document your script is running in. Origin includes domain, port, and protocol. Your loading it from the local file should only work if the document itself is loading from a local file (not an http URL). See the link for details.

Upvotes: 2

Related Questions