对于jQuery函数,使用.success()的原因是什么?初始函数会在成功后执行,对吧?那么当你包含 .success() 时,你不只是执行两次吗?
$.getJSON( "ajax/test.json", function( data ) {
//this will execute upon success
})
.success(function() {
//doesn't this do what the above is doing?
})
最佳答案
它们被设计为在每种情况下执行一个函数。成功案例、错误案例和始终执行的通用函数。
但如stated here和 here , .success()
已弃用。请参阅:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
使用这种方法,您可以在成功时执行一个函数,在失败时执行另一个函数,无论哪种情况都执行最后一个函数:
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});
关于javascript - 为什么将 .success() 与 getJSON 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31385047/