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

3
我正在尝试根据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
          }
       });
   }

有没有简单的方法来做这件事?
2个回答

6

你不能那样做。像其他ajax方法一样,.get()是异步运行的(除非你明确将其设置为同步运行,但这不是很推荐)。所以你最好做的可能是传入一个回调函数。

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

不,您需要提供一个回调函数,在请求完成后将被执行。您可以将返回值传递给回调函数。回调函数必须对结果进行操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接