最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery parsing JSON from a div - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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/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.

发布评论

评论列表(0)

  1. 暂无评论