macaroon5
macaroon5

Reputation: 35

trouble reading json data using jquery

I'm sure this is a silly oversight but I can't figure out how to get jQuery's 'getJSON' function to work. For test purposes, I have a directory set up as follows:

test.html
js/
  jquery-1.6.2.min.js
  test.js
ajax/
  test.json

and in the <head> of test.html I have the lines

<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/test.js"></script>

As a first test of the getJSON function, test.js reads as follows:

$(document).ready(function() {
    $.getJSON('ajax/test.json', function(data) {
        alert('Success!');
    });
}

However, nothing happens when the 'test.html' is loaded. I have a feeling the 'ajax/test.json' path specification is the problem, but I'm not sure why.

EDIT: My bad on the curly brace, that was actually fine in the code I just mis-copy-pasted. I opened Chrome Developer Tools and now see an XMLHttpRequest error with the explanation: "Origin null is not allowed by Access-Control-Allow-Origin".

EDIT 2: Well that's annoying.. looks like it's a Chrome issue. Works fine on Safari. As a workaround you can fire up python -m SimpleHTTPServer in the base directory and access the page at localhost:8000/test.html, in which case Chrome works fine.

Upvotes: 0

Views: 533

Answers (3)

Quentin
Quentin

Reputation: 943097

It sounds like you are trying to run this directly from a file system. Make the pages available over HTTP (by installing a web server) and use that instead.

Local webpages have lots of different security rules to HTTP webpages.

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

your code:

$.getJSON('ajax/test.json', function(data) {
   alert('Success!');
); // you missed a curly brace here. that may be a problem

CORRECT CODE:

$.getJSON('ajax/test.json', function(data) {
        alert('Success!');
});

Upvotes: 1

James Allardice
James Allardice

Reputation: 165941

You need to close your brackets correctly on the getJSON callback function and the ready function:

$(document).ready(function() {
    $.getJSON('ajax/test.json', function(data) {
        alert('Success!');
    });
});

Upvotes: 3

Related Questions