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 wi开发者_如何转开发th 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.
精彩评论