2014-09-12 88 views
0

如何使一個jQuery的CSS的進度條倒計時15秒,當窗口焦點和計數後運行一個PHP腳本?如何使一個jQuery的CSS的進度條(倒計時)?

這是一個實用小腳本,我發現它使用谷歌:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> 
    <html lang="en"> 
    <head> 
     <title>Progress Bar</title> 
    </head> 
    <body> 
    <!-- Progress bar holder --> 
    <div id="progress" style="width:500px;border:1px solid #ccc;"></div> 
    <!-- Progress information --> 
    <div id="information" style="width"></div> 
    <?php 
    // Total processes 
    $total = 10; 
    // Loop through process 
    for($i=1; $i<=$total; $i++){ 
     // Calculate the percentation 
     $percent = intval($i/$total * 100)."%"; 

     // Javascript for updating the progress bar and information 
     echo '<script language="javascript"> 
     document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\">&nbsp;</div>"; 
     document.getElementById("information").innerHTML="'.$i.' row(s) processed."; 
     </script>'; 


    // This is for the buffer achieve the minimum size in order to flush data 
     echo str_repeat(' ',1024*64); 


    // Send output to browser immediately 
     flush(); 


    // Sleep one second so we can see the delay 
     sleep(1); 
    } 
    // Tell user that the process is completed 
    echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>'; 
    ?> 
    </body> 

回答

0

下面的代碼將使一個Ajax請求被稱爲script.php php腳本當第15秒累計經過:

$(document).ready(function() { 
    var progress = $('#progress'); 
    var counter = 15; 
    var timer = 0; 

    $(window).on('focus', function() { 
     // start the countdown when the window receives focus 
     timer = setInterval(function() { 
     $(progress).html(counter); 
     // check if 15 seconds has passed 
     if(--counter == 0) { 
      // clear the interval and tell the user we're finished 
      clearInterval(timer); 
      timer = 0; 
      $(progress).html('Process complete'); 
      // make an ajax call to a php script 
      $.ajax({ 
      url:'script.php', 
      type:'post', 
      success:function(e) { 
       // handle any response     
      } 
      }); 
     } 
    }, 1000); 
    }); 

    // clear the interval and reset the counter when the window looses focus 
    $(window).on('blur', function() { 
    counter = 15; 
    if(timer) { 
     clearInterval(timer); 
     timer = 0; 
    } 
    $(progress).html(''); 
    }); 
});