【发布时间】:2017-03-14 12:40:03
【问题描述】:
我有这段代码:
getClients(id);
location.replace('/login/index.html');
我的getClients() 函数基本上是一个asyc AJAX 请求。
如果客户列表为空,它会重定向到另一个页面。这是 ajax 请求中的代码:
....
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{
....
但不知何故,如果客户端对象为空,它会先执行location.replace('/login/index.html');,然后再执行location.replace('/login/user_config.html');
我该如何解决?
【问题讨论】:
-
将
location.replace('/login/index.html');放入成功回调中。如果你需要一定的顺序来执行,你需要在使用异步函数时使用回调来定义顺序,否则运行的顺序将取决于异步方法返回需要多长时间。请注意,getClients不会等待异步完成;它会立即返回。 -
@Carcigenicate 解决了这个问题!
标签: javascript jquery ajax replace location