Created
February 29, 2012 04:30
-
-
Save jondavidjohn/1937740 to your computer and use it in GitHub Desktop.
A Simple AJAX DAL for use in a web app accessing a RESTful JSON API endpoints
This file contains 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
var AppDAL = (function() { | |
var _BASE_URL = "http://"+ window.location.host +"/api/"; | |
var _request = function(resource_uri, method, s_cback, e_cback, data) { | |
data = data || null; | |
var resource_url = _BASE_URL + resource_uri; | |
var xhr = new window.XMLHttpRequest(); | |
xhr.onreadystatechange = function () { | |
if ( xhr.readyState === 4 ) { | |
if ( xhr.status === 200 || xhr.status === 201 || xhr.status === 202 ) { | |
try { | |
parsedResponse = JSON.parse(xhr.responseText); | |
} | |
catch (e) { | |
e_cback(xhr.status, "Response Not Parsable JSON"); | |
return; | |
} | |
s_cback(parsedResponse); | |
} | |
else { | |
e_cback(xhr.status, xhr.statusText); | |
} | |
} | |
}; | |
xhr.open( method, resource_url, true ); | |
xhr.setRequestHeader( "Content-Type", "application/json" ); | |
if (data !== null) { | |
xhr.send( JSON.stringify(data) ); | |
} | |
else { | |
xhr.send(); | |
} | |
}; | |
return { | |
get : function(resource_uri, success_cback, error_cback) { | |
_request(resource_uri, "GET", success_cback, error_cback); | |
}, | |
create : function(resource_uri, data, success_cback, error_cback) { | |
_request(resource_uri, "POST", success_cback, error_cback, data); | |
}, | |
update : function(resource_uri, data, success_cback, error_cback) { | |
_request(resource_uri, "PUT", success_cback, error_cback, data); | |
}, | |
destroy : function(resource_uri, success_cback, error_cback) { | |
_request(resource_uri, "DELETE", success_cback, error_cback); | |
} | |
}; | |
})(); |
This file contains 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
(function() { | |
AppDAL.get('/resource/3', function(resource) { | |
// success! | |
}, | |
function(responseCode, msg) { | |
// error :( | |
}); | |
AppDAL.update('resource/3', updated_resource, function(resource) { | |
// success! | |
}, | |
function(responseCode, msg) { | |
// error :( | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment