【问题标题】:Why does location.replace() executes while AJAX request is still running?为什么 location.replace() 在 AJAX 请求仍在运行时执行?
【发布时间】: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


【解决方案1】:

由于这个过程是动态的,你需要等待 AJAX 响应,所以我认为你可以使用 Loader 并在向 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

【讨论】:

    【解决方案2】:

    使用@Carcigenicate 建议使用回调解决了问题。

    结果代码是这样的:

    getClients(id, location.replace('/login/index.html'));
    

    谢谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多