簡體   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