javascript - 为什么将 .success() 与 getJSON 一起使用?

标签 javascript jquery

对于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 herehere , .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/

相关文章:

JavaScript 可能存在内存泄漏

jquery - PayPal:在多个选项框之间切换?

javascript - 通过代理服务器发出 jQuery.ajax 请求

javascript - 清除数组中的空元素

javascript - 如何在 JS 中动态地使网格可分组为 false/true?

javascript - ember.js 中的 view.Image 是什么?

javascript - 如何使状态栏/地址栏在 Firefox 或 IE 中消失?

javascript - Laravel 5.3 和 Vue 2

javascript - 如何在 node.js 中流式读取目录?

jquery - 获取图像的高度以设置模态窗口大小