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

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

}

默认情况下,我将其设置为打开,但我希望用户能够禁用刷新。我怎样才能实现这个目标?

最佳答案

你的 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/

相关文章:

php - 实现自动提示的方法

javascript - 多个get请求jquery

javascript - PHP 函数未通过 ajax 调用

javascript - 如何访问代码隐藏中存储过程返回的值

javascript - 脚本 438 : Object doesn't support property or method 'debug'

javascript - 数学四分之一

javascript - 如果 API 服务器返回 http 500,AJAX 调用不会进入 "error:" block

javascript - 如何在带有 Moovweb SDK 的 Javascript 中移动 AJAX 内容?

javascript - 使用 ReadableStream 和 Response 从 Service Worker 的 fetch 事件返回 HTML

javascript - php 提交时显示警报而不加载操作链接