I wrote a ping html version, which is appears in a jQuery dialog box.
I wish that when I close the dialog box, then stop the ping.
But in my version alert the 'close' message, and again continues the ping.
<script type="text/javascript">
var init = 1;
var timestamp = null;
var tag = $("<div></div>");
function waitForMsg() {
$.ajax({
type: "GET",
url: "/modules/ping2.php?host=localhost&tsp="+timestamp+"&init="+init,
cache: false,
success: function(data) {
var json = eval('('+data+ ')');
var str = json['out'].replace(/\n/g, "<br>");
tag.html(str).dialog({
title: 'Ping',
modal: false,
width: 480,
height: 550,
close: function() {
alert('close');
}
}).dialog('open');
timestamp = json["tsp"];
init = 0;
setTimeout("waitForMsg()", 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: "+textStatus + " "+ errorThrown);
setTimeout("waitForMsg()", 15000);
}
});
}
$(function() {
$("#button").on('click', function() {
waitForMsg();
});
});
</script>
How do i cancel the polling?
If you want to stop an ajax request early, store the ajax request in a variable:
var request = $.ajax({
/* ajax params */
});
And you can abort the request when you need to like this:
request.abort();
as i pointed out in my comment :
<script type="text/javascript">
var timeout; // this is a variable the timout will be assigned to
var init = 1;
var timestamp = null;
var tag = $("<div></div>");
function waitForMsg() {
$.ajax({
type: "GET",
url: "/modules/ping2.php?host=localhost&tsp="+timestamp+"&init="+init,
cache: false,
success: function(data) {
var json = eval('('+data+ ')');
var str = json['out'].replace(/\n/g, "<br>");
tag.html(str).dialog({
title: 'Ping',
modal: false,
width: 480,
height: 550,
close: function() {
alert('close');
clearTimeout(timeout); // here we clear the timeout
}
}).dialog('open');
timestamp = json["tsp"];
init = 0;
timeout = setTimeout("waitForMsg()", 1000); // here we assign the timout
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: "+textStatus + " "+ errorThrown);
setTimeout("waitForMsg()", 15000);
}
});
}
$(function() {
$("#button").on('click', function() {
waitForMsg();
});
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.