2014-09-13 68 views
0

我有一个倒计时器,当它完成它运行一个PHP脚本(文件称为ajax.php)问题是ajax.php运行很多次。从ajax运行php

我想在表

[id][content] 
[1][timer] 

得到这个结果,但我得到这个结果

[id][content] 
[1][timer] 
[2][timer] 
[3][timer] 
[4][timer] 
[5][timer] 
[6][timer] 
[7][timer] 
[8][timer] 
[9][timer] 
..... 

这是代码

<div id="counter"></div> 

    <script src="jquery.js"></script> 
    <script> 
    var div = $('#counter'); 

    var n = 5000; 

    var blured = false; 

    var tid = setInterval(function() { 
     if (blured) return;  
     n -= 100; 
     div.text((n/1000).toFixed(1) + ' seconds passed'); 
     if (n <= 0) { 


     div.text('Time passed!'); 
     $.ajax({ 

     url: 'ajax.php', 
     type: 'post', 
     success: function(data, status) {} 

     }); 




     } 


    }, 100); 

    window.onblur = function() { 
     blured = true;  
    }; 

    window.onfocus = function() { 
     blured = false;  
    }; 


     document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\">&nbsp;</div>"; 
     // document.getElementById("information").innerHTML="'.$i.' row(s) processed."; 
     window.onblur = function() { 
      blured = true;  
     }; 
     window.onfocus = function() { 
      blured = false;  
     }; 


    </script> 

,这是阿贾克斯.php

mysql_connect("localhost","root","usbw") or die ("Couldn't connect to server"); 
    mysql_select_db("test") or die ("Coouldn't Select Database"); 


    $query = mysql_query("INSERT INTO add_delete_record VALUES ('', 'timer')"); 

回答

0
var tid = setInterval(function() { 
    if (blured) return;  
    n -= 100; 
    div.text((n/1000).toFixed(1) + ' seconds passed'); 
    if (n <= 0) { 


    div.text('Time passed!'); 
    clearTimeout(tid); 
    $.ajax({ 

    url: 'ajax.php', 
    type: 'post', 
    success: function(data, status) {} 

    }); 




    } 


}, 100); 
1

这实际上是如何工作的setInterval。从你的代码中,我可以看到你将它设置为100毫秒,因此你的浏览器会每隔0.1秒发出一次ajax调用,并且它会一直持续下去。 为了避免它,您必须首先知道函数setInterval()返回一个ID,您可以稍后使用它来清除该事件处理程序。只需使用clearInterval()

例子:

var tid = setInterval(function(){},100); 

/*Later you can use*/ 
clearInterval(tid); 

如果您需要了解更多信息结帐setInterval()clearInterval()的文档。