Перезапустите функцию успеха AJAX при ответе на ошибку json - PullRequest
0 голосов
/ 28 сентября 2018

У меня есть вызов ajax, который предназначен для запроса очереди отчета, а затем с помощью этого идентификатора снова запрашивает отчет и возвращает 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);
}

Как я могупопросить его вернуться через функцию успеха, чтобы повторить запрос отчета?

Ответы [ 2 ]

0 голосов
/ 28 сентября 2018

Во-первых, здесь вы не повторяете свой код, а просто заменяете его параметрами.Кроме того, он позволяет вызывать рекурсивно при необходимости.

$("#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);
           }
         }
    });
}
0 голосов
/ 28 сентября 2018

Если ваш результат успеха находится в формате JSON, то перед использованием расшифруйте его в массиве.

Как показано ниже

success: function(result){ 
    resultArray = $.parseJson(result); // Like this
    if (resultArray.report.error == "report_not_ready") {
    // RERUN THE SUCCESS FUNCTION
    }
    // OTHERWISE OUTPUT THE TOTAL
    $('#output2').html(resultArray.report.totals);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...