使用JQuery $ .get来确定返回值?

Wil*_*iam 3 ajax jquery

我试图根据JQuery $ .get请求的结果确定函数的返回值:

    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
          }
       });
   }
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法来做到这一点?

jAn*_*ndy 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
});
Run Code Online (Sandbox Code Playgroud)