如何通过单击从AJAX调用返回的按钮来使用clearInterval?

时间:2013-09-17 21:17:27

标签: javascript php ajax

在我的状态页面上,我有一个名为errorBarGoesHere的div id。我有一个简单的AJAX调用,每10秒运行一次,检查它是否应显示错误栏。一切正常,错误栏也会在我想要的时候显示,等等。

现在我只想关闭命令的错误栏。但是我制作的按钮无法访问或查看任何其他JS功能,因为它位于不同的页面上。我检查了网页上的源代码,当它显然在页面上显示时,甚至看不到错误栏的代码;只是errorBarGoesHere div标签是空白的。

有没有办法可以使用我制作的按钮来清除间隔?代码如下。

Javascript

var setErrorBarId = window.setInterval(function(){runErrorBarAjax();}, 10000);

function runErrorBarAjax() {
    var xmlhttp = getAjaxObject();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            processErrorBarResponse(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", "lib/errorBar.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();
}
function processErrorBarResponse(response){
    document.getElementById(\'errorBarGoesHere\').innerHTML = response;
}

errorBar.php

session_start(); // Start the session from here.

if(isset($_SESSION['errorBarError'])){
    echo '
    <link rel="stylesheet" type="text/css" href="main.css" media="screen" />
    <div id="errorBar">
        <div id="innertube">
            <h2><center>
                <div id="errorBarCaution"><img src="../images/caution.png" width="18" height="18"></div>'.$_SESSION['errorBarError'].'
            </center></h2>
            <input type="image" src="../images/closeButton.png" width="20" height="20" onclick="clearInt(setErrorBarId);">
        </div>
    </div>
    ';
    unset($_SESSION['errorBarError']);
}

1 个答案:

答案 0 :(得分:0)

最好的方法是使用jQuery。 你的文件可以是......

<html>
<head>
    <link rel="stylesheet" type="text/css" href="main.css" media="screen" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    <div id="errorBarGoesHere"></div>
    <input id="remove" type="image" src="../images/closeButton.png" width="20" height="20" />
    <script type="text/javascript">
        $(document).ready(function() {
            var setErrorBarId = window.setInterval(function(){
                $("#errorBarGoesHere").load("lib/errorBar.php");
            }, 10000);
            $("#remove").on('click', function() {
                window.clearInterval(setErrorBarId);
                $(this).remove();
            });
         });
     </script>
</body>
</html>

errorBar.php ..

session_start(); // Start the session from here.

if(isset($_SESSION['errorBarError'])){
    echo '
    <div id="errorBar">
        <div id="innertube">
            <h2><center>
                <div id="errorBarCaution"><img src="../images/caution.png" width="18" height="18"></div>'.$_SESSION['errorBarError'].'
            </center></h2>
        </div>
    </div>
    ';
    unset($_SESSION['errorBarError']);
}