Ajax call to return a task status? ( in progress O

2019-09-11 12:15发布

I have a html table with tasks and the last column is called "status". I need to do a simple thing, to track the status of each task with the usual way of an animating gif icon if its in progress or an ok check if its done.

I have done this in the past by calling a php script with $.ajax that it was refreshing itself every 1 minute. The script was a PHP script with one query that checked a boolean column. This approach was ok, but even then I knew that this was most probably the dumbest way to do something like this.

I am looking for a more robust way to do this and while I was searching I found this snippet

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('/path/to/your/php/file/userCount.php');
}, 3000); // the "3000" here refers to the time to refresh the div.  it is in milliseconds.
});
</script>

Something like this could work but how do I stop this refresh if the task was actually finished? Something like "Gaurav Sharma" answer on this post is the way to go?

I am a newbie in Jquery so I would really love to know how would you do something like this, seems a common task so I hesitate to re-invent the wheel by writing 2 pages of code for something that can be done with 5 lines :-)

2条回答
何必那么认真
2楼-- · 2019-09-11 12:50
var interval = setInterval(function() {
    $('#divToRefresh').load('/path/to/your/php/file/userCount.php');
    if(somecondition){
        clearInterval(interval);
    }
}, 3000); // the "3000" here refers to the time to refresh the div.  it is in milliseconds.

calling clearInterval(interval) stops the repetition.

查看更多
小情绪 Triste *
3楼-- · 2019-09-11 13:04

you should implement some code like this

var interval = null; // has to be global in this example

// [...] your code

interval = setInterval(function(...));

// [...] your code

if your script completes just call clearInterval(interval) from anywhere

查看更多
登录 后发表回答