繁体   English   中英

自动刷新在PHP页面上运行的ajax div

[英]auto refresh ajax div running on php page

请在下面查看我的代码。 我想在PHP页面上自动刷新div 我试图通过javascript和html标头刷新,但它正在缓慢降低我的计算机的速度。

使page2.php

<?php

if($_GET['type']!='ajax'){
    include 'header.php';
    echo "<div id='main-content'>";
}
?>
Itm 1</br>
Itm 2

<img class="ajax-loader" src="ajax-loader.gif" alt="loading..." />

<?php
if($_GET['type']!='ajax'){
    echo "</div>";
    include 'footer.php';
}?>

app.js

$.cergis = $.cergis || {};
$.cergis.loadContent = function () {
    $('.ajax-loader').show();
     $.ajax({
         url: pageUrl + '?type=ajax',
        success: function (data) {
            $('#main-content').html(data);
            // hide ajax loader
            $('.ajax-loader').hide();

  }
    });
    if (pageUrl != window.location) {
        window.history.pushState({ path: pageUrl }, '', pageUrl);
    }
}
$.cergis.backForwardButtons = function () {
    $(window).on('popstate', function () {
        $.ajax({
            url: location.pathname + '?type=ajax',
            success: function (data) {
                $('#main-content').html(data);
            }
        });
    });
}
$("a").on('click', function (e) {
    pageUrl = $(this).attr('href');
    $.cergis.loadContent();
    e.preventDefault();
});
$.cergis.backForwardButtons();

我尝试了不同的变化,但没有运气。 请帮我。

谢谢。

app.js已更改...

function myTimer() {
  $('.ajax-loader').show();
  $.ajax({
      url: pageUrl + '?type=ajax',
      success: function (data) {
          $('#main-content').html(data);
          // hide ajax loader
          $('.ajax-loader').hide();
        }
  });

}

setInterval(function(){myTimer()}, 1000);

尝试setTimeout:

function myTimer() {
  $('.ajax-loader').show();
  $.ajax({
      url: pageUrl + '?type=ajax',
      success: function (data) {
          $('#main-content').html(data);
          // hide ajax loader
          $('.ajax-loader').hide();
          setTimeout(myTimer,1000);//so that the request ends setTimeout calls a new request.
      },
      error: function () {
          setTimeout(myTimer,1000);//If there is an error in the request the "autoupdate" can continue.
      }
  });
}
myTimer();//fire

这样setTimeout()等待完成请求以调用新请求。

setInterval()不等待,这会使simuntaneos生成多个事件,从而导致运行缓慢。

您可以使用setTimeout($.cergis.loadContent, 1000); 刷新一次或setInterval($.cergis.loadContent, 1000); 刷新每秒钟(1000毫秒= 1秒)。

参见http://www.w3schools.com/js/js_timing.asp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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