2017-01-26 36 views
0

問題輪詢使用jQuery和AJAX的服務器沒有初始延遲

大家好,我試圖刷新10秒設定的時間間隔我的表中的數據......問題是,當我最初加載頁面有10秒的延遲之前顯示我的表...

代碼

標記

<h2>Employee List</h2> 
<!-- table --> 
<table class="table table-striped table-hover table-responsive"> 
    <thead> 
     <tr> 
      <td>ID</td> 
      <td>Emplyee Name</td> 
      <td>Address</td> 
      <td>Created at</td> 
      <td>Action</td> 
     </tr> 
    </thead> 

    <!-- table content dynamically generated by the javascript --> 
    <tbody id="showdata"></tbody> 
    <!-- end content --> 

</table> 
<!-- end table --> 

jQuery的

$(function(){ 


     pollServer(); 

     function pollServer(){ 

      window.setTimeout(function() { 
       alert('hey'); 
       $.ajax({ // this is a json object inside the function 
        type: 'ajax', 
        url: '<?php echo base_url('employee/showAllEmployee'); ?>', 
        async: false, 
        dataType: 'json', 
        success: function(data){ 
         console.log(data); 
         var html = ''; 
         var i; 
         for(i = 0; i < data.length; i++){ 
          html += '<tr>' + 
             '<td>' + data[i].employee_id + '</td>' + 
             '<td>' + data[i].employee_name + '</td>' + 
             '<td>' + data[i].address + '</td>' + 
             '<td>' + data[i].created_at + '</td>' + 
             '<td>' + 
              '<div class="pull-right">' + 
               '<a class="btn btn-info btn-xs item-edit" href="javascript:;" data="' + data[i].employee_id + '">Edit</a>' + 
               '<a class="btn btn-danger btn-xs item-delete" href="javascript:;" data="' + data[i].employee_id + '"><i class="fa fa-times"></i></a>' + 
              '</div>' + 
             '</td>' + 
            '</tr>' 
         } 
         $('#showdata').html(html); 
        }, 
        error: function(){ 
         alert('Could not get Data from Database'); 

        }, 
        complete: function(){ 
         pollServer(); 
        } 
       }) 
      }, 10000); 
     } 
    }); 

問題

如何讓我的網頁上加載數據,然後此後每隔10秒ping服務器?

+0

您使用'setTimeout'而不是'setInterval' – ppasler

+3

大聲笑 - 他確實使用setTimeout! –

+0

你是否在'console.log(data);上正確獲取數據? –

回答

4

變化pollServer如下

function pollServer(){ 
    $.ajax({ // this is a json object inside the function 
    // removed for clarity 
     complete: function(){ 
      setTimeout(pollServer, 10000); 
     } 
    }); 
} 
+0

這工作就像...完美。 –

1

只需調用同一個函數內部它與超時成功回調。

function pollServer() { 
    $.ajax({ 
     ... 
     success: function(data) { 
     setTimeout(function() { 
      pollServer(); 
     },10000); 
     } 
    }); 
} 

// Call the function on load 
pollServer();