I'm a beginner at jQuery and I'm trying to parse JSON data from a div using the $.getJSON
function but it isn't working. Can you show me how can I do this? Here is the code I'm using:
<div id="json">
{"data":[
{"a":"b"},
{"a":"c"}
]}
</div>
<script>
$(document).ready(function() {
$.getJSON( $("#json").html() , function(json) {
$.each(json.data, function(index, value) { $('.data').append(value.a+'<br />'); } );
});
});
</script>
<div class="data"></div>
I'm a beginner at jQuery and I'm trying to parse JSON data from a div using the $.getJSON
function but it isn't working. Can you show me how can I do this? Here is the code I'm using:
<div id="json">
{"data":[
{"a":"b"},
{"a":"c"}
]}
</div>
<script>
$(document).ready(function() {
$.getJSON( $("#json").html() , function(json) {
$.each(json.data, function(index, value) { $('.data').append(value.a+'<br />'); } );
});
});
</script>
<div class="data"></div>
Share
Improve this question
edited Nov 26, 2012 at 11:52
Anthony Grist
38.3k8 gold badges64 silver badges76 bronze badges
asked Nov 26, 2012 at 11:27
user1853155user1853155
231 silver badge3 bronze badges
1
-
Out of curiosity, why are you storing your JSON in a
<div>
on the page rather than putting it in directly as a variable in your JavaScript? – Anthony Grist Commented Nov 26, 2012 at 11:50
2 Answers
Reset to default 5The $.getJSON()
method is intended to make an Ajax call to your webserver, not to grab something off the page. Try this:
$(document).ready(function() {
var data = $.parseJSON($("#json").html());
$.each(data.data, function(index, value) { $('.data').append(value.a+'<br />'); } );
});
Demo: http://jsfiddle/SyHN8/
Using $("#json").html()
will give you the content of the field as a string, which you then pass to $.parseJSON()
to get back an object that you can work with.
$.getJSON loads JSON-encoded data from the server using a GET HTTP request. You can't use it like you do.