Last active
August 29, 2015 14:00
-
-
Save laser/11158487 to your computer and use it in GitHub Desktop.
jquery basic rest api client
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
// 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