我有一个 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}
所以,我所追求的是让它以相同的结果再次尝试这段代码。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);
}
如何要求它循环返回成功函数以重试查询报告?
最佳答案
首先,在这里您不会重复代码,只是用参数替换它。此外,它还允许在需要时递归调用。
$("#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);
}
}
});
}
关于jquery - 在 json 错误响应上重新运行 AJAX 成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551638/