迭代JSON对象

时间:2016-05-09 11:39:55

标签: javascript jquery json loops iteration

我在迭代JSON对象时遇到了一些问题。我有一个JSON文件,我用AJAX,我有15个对象。在HTML中我有一个DIV,其中有3个部分:标题,正文和日期。每隔15秒,我应该使用JSON文件中的数据更新此部分。

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)
                }
            });
        }
    });
});

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"
     }]
}

2 个答案:

答案 0 :(得分:3)

  1. 你永远不应该在AJAX上运行间隔
  2. 在您的情况下,您只需调用一次服务器并循环使用相同的数据
  3. 假设您的JSON适用于您的循环,也许您的意思是

    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 after success. use always or complete if needed
      }
    }
    

    如果您需要每隔15秒使用ONE AJAX调用获得的故事列表更新DIV,那么您需要循环

    var news,cnt=0,tId;
    function render() {
      if (cnt >= news.length) {
        clearInterval(tId); // OR set cnt to 0 and do not return to re-iterate
        return;
      }
      var item = news[cnt];
      $('#header').append(item.header);
      $('#body').append(item.body);
      $('#date').append(item.date);
      cnt++;
    }
    $(function() {
    .
       succes: function(result) {
         news = result.news;
         render(); // run immediately 
         var tId = setInterval(render,150000); // and schedule next run
       }
    .
    });
    

    &#13;
    &#13;
    result = {
      "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"
      }]
    }
    
    var news, cnt = 0, tId;
    
    function render() {
      console.log(cnt,news[cnt]);
      if (cnt >= news.length) cnt = 0; // rerun
      var item = news[cnt];
      $('#header').html(item.header);
      $('#body').html(item.body);
      $('#date').html(item.date);
      cnt++;
    }
    $(function() {
      news = result.news;
      render();
      var tId = setInterval(render, 5000);
    });  
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="header"></div>
    <div id="body"></div>
    <div id="date"></div>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

修改

检查此示例。它遍历一组对象并每2秒更新一次内容:

&#13;
&#13;
var result = [
  { header: 'header0', body: 'body0' },
  { header: 'header1', body: 'body1' },
  { header: 'header2', body: 'body2' },
  { header: 'header3', body: 'body3' },
  { header: 'header4', body: 'body4' },
  { header: 'header5', body: 'body5' },
  { header: 'header6', body: 'body6' },
  { header: 'header7', body: 'body7' }
]

i = 0;
var update = setInterval(function() {
  if (result[i]) {
    $('#header').html(result[i].header);
    $('#body').html(result[i].body);
    i++;  
  } else {
    clearInterval(update);
  }  
}, 2000);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1>Header: <span id="header"></span></h1>
<h1>Body: <span id="body"></span></h1>
&#13;
&#13;
&#13;