2013-03-06 56 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