Javascript 为什么location.replace()在AJAX请求仍在运行时执行?
我有一段代码:Javascript 为什么location.replace()在AJAX请求仍在运行时执行?,javascript,jquery,ajax,replace,location,Javascript,Jquery,Ajax,Replace,Location,我有一段代码: getClients(id); location.replace('/login/index.html'); 我的getClients()函数基本上是一个asycAJAX请求。如果客户端列表为空,它将重定向到另一个页面。以下是ajax请求中的代码: 。。。。 成功:功能(数据){ var json2=$.parseJSON(JSON.stringify(data.result)); $.cookie('usu',id,{path:'/'}); 如果(json2.lengt
getClients(id);
location.replace('/login/index.html');
我的getClients()
函数基本上是一个asycAJAX
请求。如果客户端列表为空,它将重定向到另一个页面。以下是ajax请求中的代码:
。。。。
成功:功能(数据){
var json2=$.parseJSON(JSON.stringify(data.result));
$.cookie('usu',id,{path:'/'});
如果(json2.length<2&&json2[0].UserClients.length==0){
replace('/login/user_config.html');
返回false;
}
否则{
....
但不知何故,如果clients对象为空,它将首先执行
location.replace('/login/index.html');
,然后执行location.replace('/login/user_config.html'))
我如何解决这个问题?因为这个过程是动态的,您需要等待AJAX响应,所以我认为您可以使用一个加载程序并在向AJAX发送请求之前调用它,如果您的条件不匹配,那么在这种情况下,将加载程序隐藏在屏幕上 一个简短的代码可能会帮助您
beforeSend:function(){
// init loader here
},
success: function(data){
var json2 = $.parseJSON(JSON.stringify(data.result));
$.cookie('usu', id, {path: '/'});
if(json2.length < 2 && json2[0].UserClients.length === 0){
location.replace('/login/user_config.html');
return false;
}
else{
// stop loader here
beforeSend:function(){
//初始化加载程序在这里
},
成功:功能(数据){
var json2=$.parseJSON(JSON.stringify(data.result));
$.cookie('usu',id,{path:'/'});
如果(json2.length<2&&json2[0].UserClients.length==0){
replace('/login/user_config.html');
返回false;
}
否则{
//停在这里
使用@Carcigenicate建议使用回调解决了问题结果代码如下所示:
getClients(id, location.replace('/login/index.html'));
谢谢大家的帮助。Put
location.replace('/login/index.html'));
在成功回调内部。如果您需要某个执行顺序,则在使用异步函数时需要使用回调来定义顺序,否则运行顺序将取决于异步方法返回所需的时间。请注意,getClients
不会等待异步完成;它将立即返回。@Carcigenicate解决了问题!
getClients(id, location.replace('/login/index.html'));