I have a jquery ex like this..
jQuery(开发者_开发问答document).ready(function() {
var refreshId = setInterval(function() {
jQuery("#results").load('random.php?randval='+ Math.random()+'&hours='+jQuery('#hours').val()+'&mins='+jQuery('#mins').val()+'&seconds='+jQuery('#seconds').val());
jQuery("#time_spent").val(jQuery("#results").html());
}, 1000);
});
and a submit button like this
<input type="submit" name="submit" value="Stop" id="submit" />
Now if the submit button is clicked the ajax jquery load should be stopped atonce since the time interval is 1 second.
How to do . please help thanks Haan
It sounds like you're doing an Ajax refresh on a timer, but when a form is submitted, you want to cancel the refreshing. If that's the case, when your form is submitted, you'll want to use clearInterval()
to cancel the timer.
$('form').submit(function(){
clearInterval(refreshId);
});
Or you might be able to get away with doing this right in the submit button, depending on the scope of refreshId
.
<input onclick="clearInterval(refreshId);return(true);" type="submit" name="submit" value="Stop" id="submit" />
How about checking if some variable is true before doing some ajax stuff.
Javascript:
<script type="text/javascript">
function stopWorking()
{
running = false;
}
$(document).ready(function()
{
running = true;
var refreshId = setInterval(function() {
if(running!=false)
{
jQuery("#results").load('random.php?randval='+ Math.random()+'&hours='+jQuery'#hours').val()+'&mins='+jQuery('#mins').val()+'&seconds='+jQuery('#seconds').val());
jQuery("#time_spent").val(jQuery("#results").html());
}, 1000);
});
</script>
HTML:
<input type="submit" onclick="stopWorking();return(false);" />
After clicking the submit button variable 'running' is set to false ,and all jquery actions are stopped.
If you want to prevent #result from being updated after submitting the form, you should use a callback from the get request and check if you should update #result before putting the ajax result into it.
var refreshId = -1;
jQuery(document).ready(function() {
var stop = false;
refreshId = setInterval(function() {
var data = {
randval: Math.random(),
hours: jQuery('#hours').val(),
mins: jQuery('#mins').val(),
seconds: jQuery('#seconds').val()
};
jQuery.get('random.php', data, function(data){
if (!stop) {
jQuery("#results").html(data);
jQuery("#time_spent").val(data);
};
});
}, 1000);
jQuery('form').submit(function(){
stop = true;
clearInterval(refreshId);
});
});
I am going to have a wild stab in the dark at what you are asking for. So if the ajax request takes more than 1 second it should be killed?
Try setting a timeout using jQuery's $.ajax()
function.
You need to use a different ajax method - like $.get or $.post etc... because these methods return an XMLHttpRequest object that can be stored in a variable, and later used to abort the request.
see: Abort Ajax requests using jQuery
精彩评论