简体   繁体   English

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

[英]Why use .success() with getJSON?

For the jQuery function, what is the reason to use .success()? 对于jQuery函数,使用.success()的原因是什么? The initial function will execute upon success right? 初始功能将在成功后执行,对吗? So aren't you just executing twice when you include .success()? 那么,当您包含.success()时,您是否不只是执行两次?

$.getJSON( "ajax/test.json", function( data ) {
//this will execute upon success
})
.success(function() { 
  //doesn't this do what the above is doing?
 })

在这种情况下,您不需要成功函数,您已经定义了要在成功时执行的函数。

If looking it in isolation and just the happy scenario, yes: they do the same thing. 如果孤立地看它,只是看个开心的场景,是的:他们做同样的事情。 The callback as the final argument of $.getJSON gets called regardless of the result of the request. 不管请求结果如何,都将调用$.getJSON的最终参数回调。

The .success() way of doing it is inspired by Promises. .success()方式受到Promises的启发。 You can read more about them here: https://promisesaplus.com 您可以在这里阅读有关它们的更多信息: https : //promisesaplus.com

Promises set a better interface for composing many asynchronous operations as well as handling the non-successfull scenarios. Promise为组合许多异步操作以及处理不成功的方案设置了一个更好的接口。

You should use .then() instead of .success() : https://api.jquery.com/deferred.then/ 您应该使用.then()而不是.success() https://api.jquery.com/deferred.then/

They were designed to have one function executed in each case. 它们被设计为在每种情况下都执行一个功能。 A success case, an error case, and a general function that always executes. 成功案例,错误案例以及始终执行的常规功能。

But as stated here and here , .success() is deprecated. 但正如这里所述这里.success()已过时。 See: 看到:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. 弃用通知:从jQuery 1.8开始,不再使用jqXHR.success(),jqXHR.error()和jqXHR.complete()回调。 To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. 要准备将其最终删除的代码,请改用jqXHR.done(),jqXHR.fail()和jqXHR.always()。

Using this approach, you have one function to execute in case of success, another to execute in case of failure, and a final one to execute in whichever case: 使用这种方法,您有一个在成功的情况下执行的函数,在失败的情况下执行的另一个函数,无论哪种情况都可以执行的最后一个函数:

// 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" );
});

您可以看到请求何时成功。您可以在控制台中看到一条消息,诸如此类...我不知道

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM