gpt4 book ai didi

javascript - 显示或隐藏 div 不适用于异步错误 ajax 调用

转载 作者:行者123 更新时间:2023-12-01 05:20:05 25 4
gpt4 key购买 nike

我有一些函数可以进行一些 ajax 调用。
为了按照需要的方式执行所有内容,这些请求必须使用 async: false 设置。

ajax 调用一切正常。我的问题是我需要在发送请求之前显示一个 div (一个简单的 css 加载器)并在请求之后隐藏,但它没有显示。

这是我的功能:

$("#btn1").on('click', function(){  
// Apparently it does not executes this
$('.container-loader').show();
//execute the function and handle the callback
doSomeStuff(function(c){
if(!c.ok){
showModalWarning();
$('#text').append('<li>'+c.msg+'</li>');
}
else{
toastr.success('Everything is ok');
doOtherStuff($("#select").val());
}
});

var modal = document.getElementById('Modal1');
modal.style.display = "none";
return false;
});

我的 doSomeStuff() 函数发出请求:

function doSomeStuff(callback){     
//...
for (var i = 0; i < ids.length; i++) {
var Id = ids[i][0];
var ch = ids[i][1];
var tp = 2;
var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + ch;
$.ajax({
cache: "false",
async: false, //it needs to by with async false
dataType: 'json',
type: 'get',
url: url,
success: function(data) {
if (!data)
toastr.error('error' );
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error("some problem");
}
});
}
callback({ok: true});
}

知道如何处理这个问题吗?我对异步东西真的很陌生。

最佳答案

通过删除异步并更改服务器中的方法以接收数组作为参数来解决此问题。

最终脚本:

$("#btn1").on('click', function(){             
//$('.container-loader').show();
//execute the function and handle the callback
doSomeStuff(function(c){
if(!c.ok){
showModalWarning();
$('#text').append('<li>'+c.msg+'</li>');
}
else{
toastr.success('Everything is ok');
doOtherStuff($("#select").val());
}
});
});

我的 doSomeStuff() 函数发出请求:

function doSomeStuff(callback){     
//...
var tp = 2;
var url = 'http://domain.com.br:8080/datasnap/rest/TSM/Fun/' + tp + '/' + $("#select").val() + '/' + encodeURIComponent(JSON.stringify(jsonArray));
$.ajax({
cache: "false",
//async: false, //it needs to by with async false
dataType: 'json',
type: 'get',
url: url,
success: function(data) {
if (!data)
callback({ok: false});
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error("some problem");
}, complete: function(){ //hide the loader after complete
$('.container-loader').hide();
var modal = document.getElementById('Modal1');
modal.style.display = "none";
}
});
}

关于javascript - 显示或隐藏 div 不适用于异步错误 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45176231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com