2011-01-10 69 views
3

我試圖確定基於一個jQuery $不用彷徨請求的結果的函數的返回值:

function checkResults(value) { 
     $.get("checkDuplicates.php", { 
      value: value 
     }, function(data) { 
      if(data == "0") { 
      //I want the "checkResults" function to return true if this is true 
      } else { 
      //I want the "checkResults" function to return false otherwise 
      } 
     }); 
    } 

有沒有簡單的方法來做到這一點?

回答

6

你不能那樣做。 .get()就像任何其他的ajax方法異步運行(除非你明確地設置它同步運行,這不是非常值得推薦的)。所以你可以做的最好的事情就是傳遞一個回調。

function checkResults(value, callback) { 
    $.get("checkDuplicates.php", { 
     value: value 
    }, function(data) { 
     if(data == "0") { 
     if(typeof callback === 'function') 
      callback.apply(this, [data]); 
     } else { 
     //I want the "checkResults" function to return false otherwise 
     } 
    } 
} 

checkResults(55, function(data) { 
    // do something 
}); 
3

不,您需要提供一個回調,一旦請求完成就會執行回調。您可以將返回值傳遞給回調函數。回調將不得不根據結果採取行動。