2017-09-25 91 views
0

我目前正試圖讓我的AJAX在文檔每20秒加載並運行時工作。我如何去做這件事?我已經讓它每20秒工作一次,但無法在文檔加載時使它工作。任何幫助都會很棒。AJAX以設定的時間間隔運行onload並且以設定的時間間隔

<script type="text/javascript" language="javascript"> 
window.setInterval(function(){ 

var jobid = $('#jobid').text(); 
var filename = $('#filename').text(); 


    $.ajax({ 
     url: "../progress_bar.php", 
     type:'POST', 
     data: {"value1": jobid, "value2": filename}, 
     dataType: 'json', 
     success: function(responce){ 
       $("#progress").html(responce); 
      } // End of success function of ajax form 
     }); // End of ajax call 

    }, 20000); 

</script> 

由於

+0

因此,創建一個函數並調用它....並設置它的間隔.... – epascarello

回答

2

對AJAX請求的一個應該總是使用代替間隔遞歸超時(導致請求可以持續更長的時間,則時間間隔,所以有在其作出多個請求),這也解決了主要問題:

//may wrap the whole thing into an onload listener 
(function update(){ 
    $.ajax({ 
    url: "../progress_bar.php", 
    type:'POST', 
    data: {"value1": jobid, "value2": filename}, 
    dataType: 'json', 
    success: function(responce){ 
      $("#progress").html(responce); 
      //update again in 20secs: 
      setTimeout(update, 20000); 
     } 
    }); 

})(); //start immeadiately 

小演示:

console.log("load"); 
 
(function next(){ 
 
    console.log("run"); 
 
    setTimeout(next, 1000); 
 
})()