2

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>
4

2 に答える 2

5

The $.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.net/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.

于 2012-11-26T11:30:18.587 に答える
0

$.getJSON loads JSON-encoded data from the server using a GET HTTP request. You can't use it like you do.

于 2012-11-26T11:29:25.760 に答える