Абдулах Хамзиќ Абдулах Хамзиќ - 6 months ago 7
Javascript Question

Loop does not work as intended

http://codepen.io/abdulahhamzic/pen/aNexYj

I'm trying to get this loop to correctly print out ten results on the screen, but it seems like there is something wrong with my loop and I can't figure out what that is. On Mozilla, I only get the first result displayed on the screen and it seems like the loop is stuck after the first iteration, and on Chrome I get the ten results, but it looks like the loop is still running afterwards since I can't really do any styling on the newly created elements, plus I still get that loading icon on the page. Can anyone help me in fixing this loop? Here's the code:

var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=aa&limit=10&callback=?";
$(document).ready(function(){
$.getJSON(url, function(json){
for (var i = 0; i < json[1].length; i++){
document.write("<div><span class='header' style='color:red'>" + json[1][i] + "</span><br>" + json[2][i] + "</div><br>")
}
})
})

Answer

The document.write() function is dangerous and has different behaviour over different browsers. Better not use it. You can have something like the below working code:

var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=aa&limit=10&callback=?";
$(document).ready(function(){
  $.getJSON(url, function(json){
    for (var i = 0; i < json[1].length; i++){
      $("body").append("<div><span class='header' style='color:red'>" + json[1][i] + "</span><br>" + json[2][i] + "</div><br>")
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments