Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 返回局部变量或获取结果_Javascript_Jquery - Fatal编程技术网

Javascript 返回局部变量或获取结果

Javascript 返回局部变量或获取结果,javascript,jquery,Javascript,Jquery,我想退x | | |美元。去拿 或者换句话说,如果x为true,则返回x,否则执行GET调用并返回服务器提供的值 下面列出了我的尝试(理想情况下,它将遵循返回x | | y格式,可能使用匿名函数?而不是if/then) 问题是我从$返回的值。get函数似乎不是我所期望的 如果您能解释一下发生了什么,我将不胜感激 谢谢 $(function(){ function test(x,y) { if(x==true) {return true;} else{ //tes

我想退x | | |美元。去拿

或者换句话说,如果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));

});

如果您使用的是jQuery1.5或更高版本,并且是这方面的朋友。无论何时调用AJAX,都会得到Promise对象,您可以通过.done()、.fail()和.then()将函数附加到这些对象

然而!正如这篇关于deferred/promise和所有这些内容()的精彩介绍所指出的,您还可以使用$.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 ... ");
  }
};

与默认情况下的所有AJAX调用一样,
$.get
是异步的-它立即返回调用方,而不阻塞和等待结果。您需要重构
test
函数,以便在通过ajax接收到值后进行回调并调用该回调。如果x为真,是否可以这样做?是的,请立即启动回调,而不是在
$。get
。您能详细说明如何触发回调吗?我没有详细调查,但会的。坚持信仰,这是正确的答案。谢谢