2

所以我每5秒使用ajax通过POST检索一些数据,我想要实现的是如果php文件输出一些东西,然后以某种方式停止setInterval或将其设置为9999999。

这是我尝试过的:

var interval = DEFINEDFROMMYQL;
        $(function() {
            setInterval(function() {
                $.ajax({
                    type: "POST",
                    url: "url/file.php",
                    data: "whatever=2", 
                    success: function(html) {
                        $("#new").html(html);
                        if(html.lenght > 0) {
                            var interval = 99999999999999;
                        }
                   }
                });
            }, interval);
        });

我是新手,所以任何帮助将不胜感激。

4

2 回答 2

1

您可以使用clearInterval()停止启动的计时器setInterval并将错字 html.lenght更正 为html.length

// var interval = DEFINEDFROMMYQL;
$(function() {
yourInterval = setInterval(function() {
$.ajax({
           type: "POST",
           url: "url/file.php",
           data: "whatever=2", 
           success: function(html) {
                    $("#new").html(html);  

                    if(html.length > 0) {
                    ///var interval = 99999999999999;
                      clearInterval(yourInterval);
                    }
             }
         });
   }, interval);
});
于 2013-01-03T01:45:04.247 回答
1

您可以通过几种不同的方式处理此问题,但根据您的问题(“以某种方式停止 setinterval”),让我们将实现切换为 asetTimeout并将代码重构为我们可以回忆的函数。所以...

var interval = DEFINEDFROMMYQL;
$(function() {

    // establish a function we can recall
    function getDataFromServer(){
        // this encapsulates the original code in a function we can re-call
        // in a setTimeout later on (when applicable)
        $.ajax({
            type: "POST",
            url: "url/file.php",
            data: "whatever=2", 
            success: function(html) {
                $("#new").html(html);

                // only if the length is 0 do we re-queue the function
                // otherwise (becase it's setTimeout) it will just die
                // off and stop.
                if(html.lenght == 0) {
                    setTimeout(getDataFromServer, interval);
                }
           }
        });
    }
    // make an initial call to the function to get the ball rolling
    setTimeout(getDataFromServer, interval);
    // if you want it to execute immediately instead of wait out the interval,
    // replace the above line to simply:
    //getDataFromServer();
});
于 2013-01-03T01:49:46.767 回答