开发者

trouble reading json data using jquery

开发者 https://www.devze.com 2023-03-24 23:15 出处:网络
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:

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 t开发者_开发知识库ype="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.


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!');
    });
});


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!');
});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消