Created
January 5, 2011 19:46
-
-
Save dgalarza/766899 to your computer and use it in GitHub Desktop.
Restful JSON requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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