2017-01-26 6 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

あなたは 'setInterval'の代わりに' setTimeout'を使用します – ppasler

+3

lol - 彼は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(); 
関連する問題