简体   繁体   中英

Iterating through jquery json

can anyone help i have an external json file which I can connect and show data manually but when I iterate by data.length (which is 100) it only shows the 100th data.

here is the code

var url ="output.json";
$.getJSON(url, function(data) {
  for (var i=0;i <= data.length; i++) {
    $('#stage').html('<h4>' + data[i].title + '</h4>');
  }
});

Jquery .html()

I believe you replace the same content as Alastair said.

Here's a fiddle link to show the difference.

html:

<div id='stage'></div>
<div id='stage-2'></div>

javascript:

var data = [{title:1},{title:2},{title:3},{title:4},{title:5}];
var htmlString = ''
for(var i=0;i<data.length;i++){
    $('#stage').html('<h4>' + data[i].title + '</h4>');
    htmlString += '<h4>' + data[i].title + '</h4>';
}
$('#stage-2').html(htmlString);
var url ="output.json";
var htmlString = '';
$.getJSON(url, function(data) {
  for (var i=0;i <= data.length; i++) {
    htmlString+='<h4>' + data[i].title + '</h4>'
  }
   $('#stage').html(htmlString);
});

Hope this will solve your problem... Good luck :-)

I think it's because you're overwriting the #stage element with every iteration. Appending each data element might work better:

var url ="output.json";
$.getJSON(url, function(data) {
  for (var i=0;i <= data.length; i++) {
    $('#stage').append('<h4>' + data[i].title + '</h4>');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM