2013-03-06 59 views
4

我想等到ajax调用完成并返回值。等到jquery ajax请求完成并返回值

function isFileExists(url) { 
    var res = false; 
    $.ajax({ 
     type: "GET", 
     async: false, 
     url: url, 
     crossDomain: true, 
     dataType: "script", 
     success: function() { 
      res = true; 
     }, 
     error: function() { 
      res = error; 
     }, 
     complete: function() { 

     } 
    }); 
    return res; //It is always return false 
} 

我要回值 “真/错误”

请帮助我。

+1

下一次考虑使用jquery标签而不是javascript,它会使它更具体,并节省人们的时间。谢谢 – Toping 2013-03-06 13:25:44

回答

10

你不能这样做。这不是阿贾克斯如何工作。你不能依赖任何时候完成的ajax请求...或者有史以来完成。您需要做的任何工作都基于ajax请求必须在ajax回调中完成。

的jQuery可以很容易地绑定回调(因为jQuery的AJAX方法返回jqXHR实现Deferred):

var jqXHR = $.ajax({/* snip */}); 

/* millions of lines of code */ 

jqXHR.done(function() { 
    console.log('true'); 
}).fail(function() { 
    console.log('false'); 
}); 

附:如果您将async设置为false,但可以在请求运行时锁定浏览器,则可以执行想要的操作。不要这样做。然后你只有jax。

编辑:您不能合并crossDomain: trueasync: false。跨域必须是异步的。

+2

+1。忘了延期或承诺条款:) – 2013-03-06 13:25:44

+3

你的意思是'async'到'false' – 2013-03-06 13:26:05

+1

@ GabyakaG.Petrioli是的,你是对的。我会更新答案 – 2013-03-06 13:27:44

0

也许这会为你工作:

function isFileExists(url, init) { 
    var res = null; 
    var _init = init || false; 

    if (!_init) { 
     _init = true; 
     $.ajax({ 
      type: "GET", 
      url: url, 
      crossDomain: true, 
      dataType: "script", 
      success: function() { 
       res = true; 
      }, 
      error: function() { 
       res = 'error'; 
      }, 
      complete: function() { 

      } 
     }); 
    } 

    if (res==null) { 
     setTimeout(function(){ isFileExists(url, _init); }, 100); 
    } else { 
     return res; 
    } 
} 

我测试了它短暂,但是不交域。

+0

不工作settimeout()一次又一次地调用 – Sagar 2013-03-06 14:18:23

+0

是的,它应该被调用,直到ajax请求被解析。 尝试添加'超时'设置为ajax调用,将其设置为1分钟(也许),作为意味着逃生。 – ssc892 2013-03-06 14:20:49