简体   繁体   中英

When to use jQuery.ajax and when to use jQuery.post?

It seems, at the first glass, that we can use either of those. I'm wondering, however, when should we use one or the other, assuming a scenario where we can do the same thing with any of those two.

Thanks in advance, MEM

jQuery.post is a shorthand method which calls jQuery.ajax .

If you don't need any functionality not supported by the shorthand, you might as well use it.

It's defined like this:

post: function( url, data, callback, type ) {
    // shift arguments if data argument was omited
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = {};
    }

    return jQuery.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
},

The $.post is actually derived from $.ajax . You can use $.post when you want want to set the POST method in your request. $.ajax allows you to set both GET and POST request methods.

Using $.ajax allows you to set callbacks for failure, and completion, while $.post has callback only for success. Also, $.ajax allows to set a callback to be invoked before the sending of the request and set other useful parameters as timeout time , username or password if the target script needs authentication.

In short, $.post is a useful shortcut to use in the simpler situation, while $.ajax offers full control on the request.

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