jQuery .getJSON not working
I'm just learning how开发者_运维技巧 to utilise ajax/json with jquery and I've hit a brick wall that I just don't understand.
Here is my code - VERY simple code:
$("#click").click(function() {
$.getJSON("http://localhost/jsontest/a.json", function(data) {
alert("done");
});
});
Basically, load a.json and send an alert to the screen saying done.
Here are the contents of a.json:
{ "done": "37" }
That's it.
It doesn't work though... the alert is not displayed.
Any ideas folks?
I just had an issue where I didn't format the data in the file that it's retrieving right. If the JSON in the file has anything wrong with it, it fails silently. Though you can always add .fail(function) to detect the fail.
I was using: { varname:"my string" }
When I should have been using: { "varname":"mystring" }
For this reason I think it might be better to use get to retrieve the data with $.get() and then use JSON.parse() on it. This way you know whether the get or the parse failed.
I'm betting on this: you forgot to put that setup code in a <script>
block after your "click" element, or in a "ready" handler:
$(function() {
$('#click').click(function() { /* ... same stuff as you have ... */ });
});
Is there any error returned from firebug?
I'd start by changing:
$.getJSON("http://localhost/jsontest/a.json?callback=?", function(data) {
to:
$.getJSON("http://localhost/jsontest/a.json", 'callback=?', function(data) {
Try this:
$.getJSON("http://localhost/jsontest/a.json", { }, function(data) {
alert(data.done);
});
精彩评论