Ajax stands for Asynchronous JavaScript and XML and is a group of technologies used by a browser to asynchronously send and fetch data from the server. People want websites that feel faster and responsive, almost similar to desktop applications. Sites like Twitter, Facebook, Gmail, Bing Maps etc. have blurred the lines between desktop and website applications and the technology that makes this possible is Ajax. Ajax can breathe life into any user interface.
Why jQuery for Ajax?
$.ajax({ type: "GET" , url: "/someurlhere" , dataType: "json" , // text, html, xml //additional settings come here }); |
$.ajax({ type: "GET" , url: "/someurlhere" , dataType: "json" , // text, html, xml success: yourSuccessCallback, error: yourErrorCallback }); function yourSuccessCallback(data_returned, status) { // code comes here } function yourErrorCallback(request, status, error) { // code comes here }
As of jQuery 1.8, .success() and .error() are deprecated and replaced with .done() and .fail().
|
- .done(response, status, jqXHR) - called when the response from the server is successful
- .fail(jqXHR, status, error) - called when the response from the server fails or the request times out.
- .always(response, status, jqXHR) - Always called when a response is received from the server
$.ajax({ type: "GET" , url: "/someurlhere" , dataType: "json" // text, html, xml }).done( function () { //call is successful }).fail( function () { //call has failed }).always( function () { //always execute despite failure/success });
However a cleaner approach is to save the returned value of $.ajax() into a variable and then declare the callback functions on that variable. This is possible due to Deferreds which manages callbacks in a much elegant way.
|
var x = $.ajax({ type: "GET" , url: "/someurlhere" , dataType: "json" // text, html, xml }); x.done( function () { //call is successful }); x.fail( function () { //call has failed }); x.always( function () { //always execute despite failure/success });
The advantage of this approach is that it is cleaner and you can have multiple .done() and .fail() callbacks defined on the variable.
|
0 comments :
Post a Comment