jquery - 在 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);
}
我如何要求它循环返回成功函数以重试查询报告?
解决方案
首先,在这里你不是重复你的代码,只是用参数替换它。此外,它允许在需要时递归调用。
$("#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);
}
}
});
}
推荐阅读
- javascript - 子函数运行完毕返回父函数
- reactjs - 如何在 nextjs 中使用不同的 .env 文件?
- scala - 如何迭代地将 Dataframe 带回 Spark 中的驱动程序
- wso2 - 如何在 Ballerina 中获取变量的类型?
- c# - .Net Core Blazor 发生类型错误,我试图转换它,但它不起作用
- ruby-on-rails - Rails 6 Font Awesome 5 生产问题
- mysql - MySQL多对多关系计数
- python - 有没有办法对python pandas中的投资组合标准差进行矢量化
- python - Python - 使用路径打开文件
- security - JWT - 刷新令牌和安全改进