每隔一段时间执行 AJAX 请求,直到收到适当的响应



我正在使用jQuery执行AJAX请求,它工作正常,但是服务器响应在带有URL的XML响应和没有内容的XML响应之间有所不同。

实际上,这两个响应都将请求限定为"成功"或"完成",因此在处理我的 AJAX 请求的"done"事件时,我想验证响应是否不为空,如果是,请在延迟后再次尝试 AJAX 请求。

我正在研究jQuery承诺,但我不确定这是否是我想要的,但如果是,请提供一个易于理解的示例。

这就是我想要的:

    function(name, location){
        $.ajax({
            type: "POST",
            url: "some.php",
            data: { name: name, location: location }
        }).done(function( msg ) {
            if (msg.length < 1) {
                setTimeout(
                   // Perform this request again
                , 500);
            } else {
                // Go on
            }
        });
    }

只是一个猜测

//here´s a function called runAgain, waiting for two parameters, the timeout function will execute it again
function runAgain(name, location){
            $.ajax({
                type: "POST",
                url: "some.php",
                data: { name: name, location: location }
            }).done(function( msg ) {
                if (msg.length < 1) {
                    setTimeout(function(){
                       runAgain(name,location)
                    }, 500);
                } else {
                    // Go on
                }
            });
}
//This function runs when the document is ready, an calls the runAgain function 
$(function(){
   var name= "?";
   var location = "?";
    runAgain(name,location);
});

相关内容

最新更新