返回局部变量或 GET 结果

Return either local variable or GET results

本文关键字:结果 GET 局部变量 返回      更新时间:2023-09-26

我想返回 x || $.get.

或者换句话说,如果 x 为 true,则返回 x,否则执行 GET 调用并返回服务器提供的值。

下面列出了我的尝试(理想情况下,它将遵循返回 x || y 格式,也许带有匿名函数?而不是 if/then)。

问题是我从 $.get 函数返回的似乎不是我预期的。

希望解释正在发生的事情。

谢谢

$(function(){
  function test(x,y) {
    if(x==true) {return true;}
    else{
      //test.php is echo($_GET['y']==123);
      $.get('ajax.php',{'y':y},function (status) {return status;});
    }
  }
  alert(test(false,123));
});

如果你使用的是jQuery 1.5或更高版本,Deferred和Promise是你做这种事情的朋友。每当你调用AJAX调用时,你得到的是Promise对象,你可以通过.done(),.fail()和.then()将函数附加到这些对象。

然而!正如这个关于延期/承诺和所有这些东西的优秀介绍所指出的(http://www.erichynds.com/jquery/using-deferreds-in-jquery/),您还可以使用 $.wait() 的能力来处理不是自动执行缓存的承诺的值。所以像这样编码:

$.when(getToken()).done(
  function (token) {
    // do something with the token, which may or may not have been 
    // retrieved from the remote service
  }
);

可以毫无问题地处理获取缓存值或承诺:

function getToken() {
  // Return either the cached value or a jQuery Promise. If $.when() gets the
  // cached value it will immediately realize that you didn't give it a
  // promise and it will instead create a jQuery Deferred to return and
  // .resolve() it using the value it did get. Thus, either way what
  // comes out of the function is something .when() can deal with and call a function.
  if (this.cache["token"]) {
    return this.cache["token"];
  } else {
    return $.get(" ... some url ... ");
  }
};