首页 > 解决方案 > 在 json 错误响应上重新运行 AJAX 成功函数

问题描述

我有一个 ajax 调用,用于查询报告队列,然后使用该 ID 再次查询报告并返回 JSON。此代码有效:

$(document).ready(function(){
    $("#r2").click(function(){
        $('#loading').show();
        $.ajax({
        url: "report.php", 
        dataType: 'json',
        data: { 
            type: 'queue', 
            ref: 2
        },
        success: function(result){
            console.log(result.reportID); 
            setTimeout(function(){
            console.log("Go"); 
            $.ajax({
              url: "report.php", 
              dataType: 'json',
              data: { 
              type: 'get', 
              ref: result.reportID
            },
            success: function(result){ 
                console.log(result); 
                $('#loading').hide();
                $('#output2').html(result.report.totals);
            }
            });
            },1000);
        }});
    });
});

但有时,报告还没有准备好,在这种情况下,我们会以 JSON 格式而不是result.report.totals

{error: "report_not_ready", error_description: "Report not ready", error_uri: null}

所以,我所追求的是它使用相同的 result.reportID 再次尝试这段代码:

success: function(result){
    console.log(result.reportID); 
    setTimeout(function(){
    console.log("Go"); 
    $.ajax({
      url: "report.php", 
      dataType: 'json',
      data: { 
      type: 'get', 
      ref: result.reportID
    },
    success: function(result){ 
        console.log(result); 
        $('#loading').hide();
        $('#output2').html(result.report.totals);
    }
    });
    },1000);
}});

我的尝试如下:

success: function(result){ 
    if (result.report.error == "report_not_ready") {
    // RERUN THE SUCCESS FUNCTION
    }
    // OTHERWISE OUTPUT THE TOTAL
    $('#output2').html(result.report.totals);
}

我如何要求它循环返回成功函数以重试查询报告?

标签: jqueryajax

解决方案


首先,在这里你不是重复你的代码,只是用参数替换它。此外,它允许在需要时递归调用。

$("#r2").click(function(){

getReport(2, 'queue')

});

function getReport(refId, type)
{
   $.ajax({
        url: "report.php", 
        dataType: 'json',
        data: { 
            type: type, 
            ref: refId
        },
        success: function(result){
          
           if (refId == 2)
           {
               getReport(result.reportID, 'get');
           }
           else if(result.report.error == "report_not_ready") 
           {
               getReport(refId, 'get');
           }
           else
           {
              $('#output2').html(result.report.totals);
           }
         }
    });
}


推荐阅读