Javascript jQuery延迟对象

Javascript jQuery延迟对象,javascript,jquery,deferred,Javascript,Jquery,Deferred,我很难在jQuery中处理延迟对象 例如 我想我可以使用以下语法,但这实际上是在成功发生时同时运行success和fail。我认为fail只有在ajax调用失败时才会运行 checkFoo(widget) .success(step1, step2) .fail(alert("failed")); checkFoo是一个类似这样的AJAX调用 function checkFoo(widget){ return $.ajax({ url: "foo.php",

我很难在jQuery中处理延迟对象

例如

我想我可以使用以下语法,但这实际上是在成功发生时同时运行success和fail。我认为fail只有在ajax调用失败时才会运行

checkFoo(widget)
.success(step1, step2)
.fail(alert("failed"));
checkFoo是一个类似这样的AJAX调用

function checkFoo(widget){
   return $.ajax({
          url: "foo.php",
          data: widget,
          format: json
   });
}
这很糟糕:

.success( step1(), step2() )
这将把执行
step1()
step2()
的结果作为参数传递

但这是好的

.success( step1, step2 )
它将传递函数本身,以便稍后执行。

这是错误的:

.success( step1(), step2() )
这将把执行
step1()
step2()
的结果作为参数传递

但这是好的

.success( step1, step2 )

它将传递函数本身,以便稍后执行。

您使用它们的方式不对

.success()
.fail()
将回调函数作为参数

所以试试看

checkFoo(widget)
.success( function(){
    step1(); 
    step2();
})
.fail( function(){
    alert("checkfoo failed");
});

你用错了方法

.success()
.fail()
将回调函数作为参数

所以试试看

checkFoo(widget)
.success( function(){
    step1(); 
    step2();
})
.fail( function(){
    alert("checkfoo failed");
});

我想您可能想将fhnction表达式传递到
fail

.fail(function() {

});

我想您可能想将fhnction表达式传递到
fail

.fail(function() {

});
你的代码

checkFoo(widget)
.success( step1(), step2() )
.fail( alert("checkfoo failed") );
立即调用
步骤1
步骤2
警报
,并将其返回值传递到
成功
失败
方法。一模一样

foo(bar());
…调用
bar
并将其返回值传递到
foo

如果要让jQuery在成功时调用
step1
step2
,并在失败时发出
警报,请传入函数引用:

checkFoo(widget)
.success( step1, step2 )      // <== No parens, `step1` refers to a *function*
.fail( function() {           // <== Wrap a function around the alert
    alert("checkfoo failed");
});
checkFoo(小部件)
.success(步骤1、步骤2)//您的代码

checkFoo(widget)
.success( step1(), step2() )
.fail( alert("checkfoo failed") );
立即调用
步骤1
步骤2
警报
,并将其返回值传递到
成功
失败
方法。一模一样

foo(bar());
…调用
bar
并将其返回值传递到
foo

如果要让jQuery在成功时调用
step1
step2
,并在失败时发出
警报,请传入函数引用:

checkFoo(widget)
.success( step1, step2 )      // <== No parens, `step1` refers to a *function*
.fail( function() {           // <== Wrap a function around the alert
    alert("checkfoo failed");
});
checkFoo(小部件)

.成功(第1步,第2步)//谢谢你的提示。你知道为什么在我上面的例子中,即使我的ajax调用成功了,fail仍在运行吗?你可能想使用
。然后(成功,失败)
或者使用
。失败(失败)。成功(成功)
就像我认为的那样。
。成功(func1,func2)
只是指出解决问题时要运行的两件事。@JasonWells,因为同样的问题。您正在调用
alert()
,然后将结果作为回调提供。你需要传入一个函数。这一点很好@AlexWayne,因此alert()需要包装在
function(){alert(…)}
中,谢谢你的提示Alex。你知道为什么在我上面的例子中,即使我的ajax调用成功了,fail仍在运行吗?你可能想使用
。然后(成功,失败)
或者使用
。失败(失败)。成功(成功)
就像我认为的那样。
。成功(func1,func2)
只是指出解决问题时要运行的两件事。@JasonWells,因为同样的问题。您正在调用
alert()
,然后将结果作为回调提供。您需要传入一个函数。这一点很好@AlexWayne,因此alert()需要包装在
function(){alert(…)}
jQuery 1.8中不推荐使用success方法。您应该使用done而不是success。jQuery 1.8中不推荐使用success方法。你应该用“完成”而不是“成功”。谢谢T.J,这就是我最后要做的。我也继续前进,把成功变成了成功。谢谢T.J,这就是我最后所做的。我也继续前进,把成功变成了成功。