简体   繁体   中英

Why use .success() with getJSON?

For the jQuery function, what is the reason to use .success()? The initial function will execute upon success right? So aren't you just executing twice when you include .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.

The .success() way of doing it is inspired by Promises. You can read more about them here: https://promisesaplus.com

Promises set a better interface for composing many asynchronous operations as well as handling the non-successfull scenarios.

You should use .then() instead of .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. See:

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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