Making requests to the server with jQuery
There are several ways to make reque开发者_JAVA技巧sts to the server using jQuery.
.load()
.post()
.get()
.ajax()
For uniformity throughout my application I always use .ajax()
.
But I'm wondering if this really is a good approach.
So... is it?
The other methods (post
, load
, and get
) are just shorthand ways of invoking the ajax
method, so it's a matter of style/convention.
There is nothing wrong with using ajax throughout your app.. I would infact advice this..
If I had to give a small analogy of get, post and ajax its like you would be able to buy yourself a completed car, with a friendly interface (pedals, steering wheel etc.) so you don't have to do it all yourself.
$.get, $.post etc. are used for higher-level abstractions that are often easier to understand and use, but don’t offer as much functionality (such as error callbacks).
To summarize:
$.load(): Load a piece of html into a container DOM.
$.get(): Use this if you want to make a GET call and play extensively with the response.
$.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
$.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.
Hope that makes sense..
Its just a matter of preference, i myself have never used any of these short cuts.
.load(), .post(), .get()
, are just short hands, internally they all relly on $.ajax
.
To test they all internally call $.ajax
, you can hack $.ajax
as below
var capturedAjax= $.ajax;
$.ajax=function myCustomAjax(options)
{
options.beforeSend=function()
{
alert('before send captured');
}
return capturedAjax(options);
}
jQuery.get('http://google.com');
http://jsfiddle.net/praveen_prasad/LBBhf/
Limiting yourself to only using .ajax()
is a bad idea. Here is an analogy to explain why:
Anna and Joe each have a toolbox containing an all-in-one tool with all sorts of attachments, a belt sander, a power drill, a table saw, and a bunch of screws. They both need to build a wooden cabinet using the tools at their disposal and an ample supply of wood. Joe decides to use the all-in-one tool and simply change attachments as needed. Anna, however, realizes that it will be easier and faster to build the cabinet using tools made for a specific purpose and decides against using the all-in-one tool to do everything. Anna is able to build a better cabinet in less time because she chose to use tools designed for a specific purpose instead of the all-in-one tool.
Analogy Updated to compare an all-in-one tool vs multiple specialized tools, which more accurately reflects the comparison of ajax vs get, post, and load. Thanks for the suggestion!
精彩评论