首页 > 解决方案 > 如何根据响应间隔发送 Ajax 请求

问题描述

如何在内部时间发送ajax请求但也取决于响应?如果响应满足某些条件,则不再发送 ajax。太感谢了!

示例代码

function send_ajax_on_interval(){
    $.ajax({
        type: "GET",
        async: true,
        url: ...
        data: ...
        dataType: "json",
        success: function (response) {
            status = response['stat_code'];
            if (status == 0) {
               // stop sending requests, otherwise continuously send in every 5 seconds
         
        },
        complete:function(){
        
        },
        error: function () {
        }
    });
}

标签: jqueryajax

解决方案


您必须在变量中创建间隔,清除它并重新初始化它;

 var ajaxInterval;
 ajaxInterval = setInterval(send_ajax_on_interval(),5000);

如果条件为真,清除它

if(status == 0){
     clearInterval(ajaxInterval);
}

推荐阅读