Артур Поляков Артур Поляков - 6 months ago 12
Javascript Question

Iterating through JSON objects

I have a little problem with iterating through JSON objects. I have a JSON file which I get with AJAX, I have there 15 objects. In HTML I have a

DIV
in which are 3 sections: header, body and date. Every 15 sec I should update this sections with data from JSON file.

Here is my HTML:

<div class="blog">
<span id="header">
Blog
</span>
<span id="body">
20+ Best Examples of <br>
Coming Soon Page Design
</span>
<span id="date">
May 28, 2013
</span>
</div>


JavaScript:

$(function() {
$.ajax({
url: "news.json",
success: function(result) {
var headCont = $('#header');
var bodyCont = $('#body');
var dateCont = $('#date');
var res = result.news;

$.each(res, function(index, element) {
for (header in res) {
setInterval(function() {
headCont.html(element.header);
}, 15000)
}
});
}
});
});


Here is JSON:

{
"news": [
{
"header": "Microsoft is starting a private beta for its iPhone
keyboard",
"body": "Microsoft has its own mobile operating system, but that
hasn't stopped it from opening a public beta for a new iPhone
keyboard.",
"date": "2016-04-14T08:40:23.449Z"
},
{
"header": "Microsoft sues U.S. government over data gag orders",
"body": "Microsoft wants a federal court to invalidate part of a 1986
law that it alleged has been abused by the government when
authorities demand customers' data.",
"date": "2016-03-14T08:40:23.449Z"
}
]
}

Answer
  1. You should never run interval on Ajax
  2. In your case you only call the server once anyway as I commented ealier

Assuming your JSON works with your loop, perhaps you meant

function updateIt() {
   var headCont = $('#header');
   var bodyCont = $('#body');
   var dateCont = $('#date');
   $.ajax({
    url: "news.json",
    success: function(result) {
      var res = result.news;
      $.each(res, function(index, element) {
        for (header in res) {
          headCont.append(element.header);
        }
      });
    });
    setTimeout(updateIt,15000); // run again after success. us always or complete if needed
  }
}

IF I misunderstood and you need to update the DIV every 15 seconds with the list of stories gotten with ONE ajax call, then you need to create an array of headers and loop with

var headers,cnt=0;
function render() {
  if (cnt >= headers.length) return;
  $('#header').append(headers[cnt]);
  cnt++
  setTimeout(render,150000);
}
$(function() {
.
   for (header in res) {
     headers.push(element.header);
   }
   render();
.
});
Comments