通过选择单选按钮启动和停止AJAX

时间:2015-08-17 22:27:41

标签: javascript ajax

我有一个只有两个单选按钮的小表单。要打开自动检查,要打开一个以禁用它:

<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();
    }

}

默认情况下,我将其设置为on,但我希望用户能够禁用刷新。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

您的HTML变为:

 <input type="radio" id="refreshOff" name="perCheck" value="off" onclick="disableAutoRefresh();" onclick="getTweets()">Periodic Checking Off

您声明新变量global并定义新函数:

var autoRefresh = true
function disableAutoRefresh(){
    autoRefresh = false;
}

您修改代码

if(document.getElementById('refreshOn').checked) {
    setInterval(function () {if (autoRefresh) sendRequest()}, 2000);
    //rest of your code
    //...
}

答案 1 :(得分:1)

将间隔设置为变量并根据用户输入清除变量

var theInterval;

if(document.getElementById('refreshOn').checked) {

    theInterval = 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();
    }

}
$('input').click(function(){
  if(document.getElementById('refreshOff').checked){
    clearInterval(theInterval);
  }
});