Skip to content

Instantly share code, notes, and snippets.

@dgalarza
Created January 5, 2011 19:46
Show Gist options
  • Select an option

  • Save dgalarza/766899 to your computer and use it in GitHub Desktop.

Select an option

Save dgalarza/766899 to your computer and use it in GitHub Desktop.
Restful JSON requests
/**
* Extend the jQuery ajax methods to make JSON requests
* available to all the RESTful CRUD operations
* (POST, PUT, DELETE)
*
* Also overwrites the default getJSON method to provide the option
* for a separate method for handling errors
*
* @author Damian Galarza (galarza.d@gmail.com)
*/
(function ($) {
/**
* Method that actually makes the request, xJSON convenience methods
* proxy to this method to make things as DRY as possible
*
* @param {Array} args Array of args from original convenience method
* @option args {String} url The URL to request
* @option args {Object} data Data to send with request
* @option args {Function} success Callback to fire upon successful request
* @option args {Function} error Callback to fire upon request error
*/
var ajax_request = function(type, args) {
$.ajax({
type: type,
url: args[0],
data: args[1],
success: args[2],
error: args[3],
beforeSend: function(xhr) {
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
}
})
};
/**
* Retreive JSON from a server via specified method:
* getJSON, postJSON, putJSON, deleteJSON
*
* @param {Array} args Configuration Data
* @option args {String} url The URL to request
* @option args {Object} data Data to send with request
* @option args {Function} success Callback to fire upon successful request
* @option args {Function} error Callback to fire upon request error
*/
$.getJSON = function() {
ajax_request('GET', arguments);
};
$.postJSON = function() {
ajax_request('POST', arguments);
};
$.putJSON = function() {
ajax_request('PUT', arguments);
};
$.deleteJSON = function() {
ajax_request('DELETE', arguments);
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment