Skip to content

Instantly share code, notes, and snippets.

@laser
Last active August 29, 2015 14:00
Show Gist options
  • Save laser/11158487 to your computer and use it in GitHub Desktop.
Save laser/11158487 to your computer and use it in GitHub Desktop.
jquery basic rest api client
// REST API Client Definition
var apiClient = (function() {
var ajax = function(url, type, callback, data) {
var config = {
dataType: 'json',
error: function(xhr, status, text) {
return callback({
xhr: xhr,
status: status,
text: text
}, null);
},
success: function(o, status, xhr) {
return callback(null, o);
},
url: url,
type: type
};
if (type.toLowerCase() === 'post') {
config['data'] = data;
}
return $.ajax(config);
};
return {
readTodos: function(callback) {
ajax('/todos', 'put', callback);
},
createTodo: function(callback, todo) {
ajax('/todos', 'post', callback, todo);
},
updateTodo: function(callback, todo) {
ajax('/todos/' + todo['id'], 'put', callback, todo);
},
deleteTodo: function(callback, todo) {
ajax('/todos/' + todo['id'], 'delete', callback);
}
};
}());
// REST API Client Usage
apiClient.readTodos(function(err, todos) {
$('#todos').text(JSON.stringify(todos));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment