自动刷新json而不重新加载

时间:2015-12-16 11:03:31

标签: javascript jquery json

我正在尝试制作一个自动刷新json,它每5秒重新加载一次更改。它在加载时第一次完全加载,但我的setinterval无法正常工作。这是每5秒钟,但即使已经进行了更改,它也不会更新我的菜单? 。

这是我到目前为止所得到的:

 $(document).ready(function(load) {

    var dmJSON = "example.com";

    $.getJSON( dmJSON, function(data) {


    setInterval(function () {
      $(news).html(""); 
      $.getJSON();         
    }, 5000);

    var html = '';

 // loop through all the news items, and append the 
 // title and published date to the html variable.

 for(var i = 0; i < data.feed.data.length; i++){

    html += '<div style="width: 600;direction: rtl;background-color: white;padding: 12px 12px 0;border: 1px solid;border-color: #e5e6e9 #dfe0e4 #d0d1d5;border-radius: 4px;margin-bottom: 20px;color: black;">';

    html += '<span style="/* text-align: left; */direction: rtl;position: absolute;left: 250px;"> ' + data.feed.data[i].created_time + ' </span><span><img alt="" src="http://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Network-Globe-Disconnected-icon.png" style="background-size:auto;background-repeat: no-repeat;display: inline-block;height: 20px;width: 20px;position: absolute;left: 490px;padding-top: 9px;" /></span>' ;

    html += '<br>' ;

    html += data.feed.data[i].message ;

    html += '<p><img alt="" src=' + data.feed.data[i].picture + ' /></p>';

    html += '</div>';

 }

 // append all the html variable to the ticker div.
    $("#news").append(html);
 });

 });

我使用此代码,但在刷新时,他会给我的空页

setInterval(function () {
  $(news).html(""); 
  $.getJSON();         
}, 5000);

1 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function(load) {

 var dmJSON = "https://";
 function fetch() {
   $.getJSON( dmJSON + (+new Date()), function(data) {
     $("#news").html('');
     var html = '';

     // loop through all the news items, and append the 
     // title and published date to the html variable.

     for(var i = 0; i < data.feed.data.length; i++){

         html += '<div style="width: 600;direction: rtl;background-color: white;padding: 12px 12px 0;border: 1px solid;border-color: #e5e6e9 #dfe0e4 #d0d1d5;border-radius: 4px;margin-bottom: 20px;color: black;">';

         html += '<span style="/* text-align: left; */direction: rtl;position: absolute;left: 250px;"> ' + data.feed.data[i].created_time + ' </span><span><img alt="" src="http://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Network-Globe-Disconnected-icon.png" style="background-size:auto;background-repeat: no-repeat;display: inline-block;height: 20px;width: 20px;position: absolute;left: 490px;padding-top: 9px;" /></span>' ;

         html += '<br>' ;

         html += data.feed.data[i].message ;

         html += '<p><img alt="" src=' + data.feed.data[i].picture + ' /></p>';

         html += '</div>';

      }

      // append all the html variable to the ticker div.
      $("#news").append(html);
   });
 }
 setInterval(fetch, 5000);// call fetch every 5 seconds
 fetch(); // call fetch first time
});