我有一个小表单,只有两个单选按钮。要打开自动检查并禁用它:
<form class="user-containter-form">
<input type="radio" id="refreshOn" name="perCheck" value="on" checked="checked">Periodic Checking On<br>
<input type="radio" id="refreshOff" name="perCheck" value="off" onclick="alert('hello');" onclick="getTweets()">Periodic Checking Off
</form>
我有一个 AJAX 请求来实际获取信息。
if(document.getElementById('refreshOn').checked) {
setInterval(function () {sendRequest()}, 2000);
function sendRequest(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
document.getElementById("test").innerHTML=xmlhttp.responseText;
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}
xmlhttp.open("GET","getTweets.php?",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
}
默认情况下,我将其设置为打开,但我希望用户能够禁用刷新。我怎样才能实现这个目标?
最佳答案
你的 html 变成:
<input type="radio" id="refreshOff" name="perCheck" value="off" onclick="disableAutoRefresh();" onclick="getTweets()">Periodic Checking Off
您声明新变量全局并定义新函数:
var autoRefresh = true
function disableAutoRefresh(){
autoRefresh = false;
}
您修改代码
if(document.getElementById('refreshOn').checked) {
setInterval(function () {if (autoRefresh) sendRequest()}, 2000);
//rest of your code
//...
}
关于javascript - 通过选择单选按钮启动和停止 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060718/