A wrapper for so-called "AJAX" Requests
I've made JHRW to:
- Advance my JavaScript skills;
- Improve/Simplify the usage of the XMLHttpRequest object by:
- Adding default values to what's undefined;
- Adding additional Error checking and clarification;
- Adding interesting, simplified, feature, such as timeouts and retries.
Object JHRW(String base, String urlPath [, Boolean lazyExecution = false [, Boolean bypassCache = false]]);String base- The request's base URLString urlPath- The request's endpointBoolean lazyExecution(optional) - If the request should be initialized and sent right after instantiation. Default: falseBoolean bypassCache(optional) - If the request URL should have a timed parameter added in order to bypass cache. Default: false
- A
ReferenceError- If there's no JHRWHandler function defined.
- A
Error- if the base parameter is
undefined - if the urlPath parameter is
undefined
- if the base parameter is
- A
TypeError- if the base parameter is not a
String - if the urlPath parameter is not a
String - if the lazyExecution parameter is not a
Boolean - if the bypassCache parameter is not a
Boolean
- if the base parameter is not a
An Object containing:
Object request- The native XMLHttpRequest ObjectObject config- The configuration ObjectString URI- The request's targetBoolean asynchronous- If the request should be asynchronousString verb- The HTTP verbMixed data- Data to be sent along with the requestObject requestHeaders- HTTP headers for the requestString responseType- Expected MIME type of the responseObject handlers- The functions to handle the requestNumber attempts- # of attempts to retry if the request failsNumber attemptInterval- Interval between attempts, in seconds.Number timeout- The timeout, in seconds, for the request - after which it should be retried.Function postTimeout: The function to be executed if the request times out.Number timer- The timer that controls the retry process.
Array JHRW.availableHandlers: The types of handlers that can be [re-]defined.String JHRW.handlerList: Convenience property to be shown in error messages.
void configure(Object configureObject);Overwrites one or more configuration options (see the config object above)
void init();Initializes the request: Sets the expected response MIME Type; Sets the handlers as listeners; Opens the request; Sets the request's headers.
void send();Sends the request, including data, if available.
void end();Ends the request. Useful if you wish for JHRW to stop retrying on success.
try {
var obj = new JHRW('http://localhost', /foo.php', true);
} catch (Error e) {
// Do something
}or
try {
var req = new JHRW('http://localhost', 'foo.php');
try {
req.init();
} catch (ReferenceError e) {
// Do something
}
req.send();
} catch (Error e) {
// Do something
}For a more advanced usage example see the testing page.
- Developed by @galvao.
- Logo font: Neutra Text Bold
