Skip to content

Instantly share code, notes, and snippets.

@Poetro
Created February 19, 2011 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Poetro/835017 to your computer and use it in GitHub Desktop.
Save Poetro/835017 to your computer and use it in GitHub Desktop.
HTTPClient class
// http://svn.janoszen.com/repos/jsfw/trunk/httpclient.js
function HTTPClient() {
this._xhr = this._getXHR();
}
HTTPClient.prototype = {
_xhr : undefined,
_method : "GET",
_url : "",
_data : "",
_callbacks : {
open: [],
headers: [],
loading: [],
done: [],
successful: [],
error: []
},
_methods: {
GET : "GET",
HEAD : "HEAD",
POST : "POST",
PUT : "PUT",
DELETE : "DELETE",
OPTIONS : "OPTIONS"
},
setMethod : function (method) {
if (method in this._methods) {
this._method = method;
}
else {
throw "Invalid HTTP method: " + method;
}
},
setURL : function (url) {
this._url = url;
},
setData : function (data) {
this._data = data;
},
send : function () {
this._xhr.open(this._method, this._url, true);
this._xhr.onreadystatechange = this._callbackHandler;
this._xhr.send(this._data);
},
isError : function () {
var re = /^4|5/;
if (re.test(this._xhr.status)) {
return true;
} else {
return false;
}
},
onOpened : function (callback) {
this._callbacks.open.push(callback);
},
onHeadersReceived : function (callback) {
this._callbacks.headers.push(callback);
},
onLoading : function (callback) {
this._callbacks.loading.push(callback);
},
onDone : function (callback) {
this._callbacks.done.push(callback);
},
onDoneSuccessful : function (callback) {
this._callbacks.successful.push(callback);
},
_getXHR : window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
function () {
return new window.XMLHttpRequest();
} :
function () {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
throw "No HTTP client library available!";
},
_callback : function (func, xhr) {
var callbacks = this._callbacks[func], i;
if (callbacks) {
for (i in callbacks) {
if (Object.prototype.hasOwnProperty.call(callbacks, i)) {
try {
callbacks[i](xhr);
} catch (e) {
Error.handle(e);
}
}
}
}
},
_callbackHandler : function () {
switch (this.readyState) {
case 1:
this._callback('open', this);
break;
case 2:
this._callback('headers', this);
break;
case 3:
this._callback('loading', this);
break;
case 4:
this._callback('done', this);
if (this.isError()) {
this._callback('error', this);
} else {
this._callback('successful', this);
}
break;
}
}
};
/**
* @todo Define relation between HTTPClient and HTTP.
*/
var HTTP = {
init: function () {
}
};
Bootstrap.registerModule("HTTP");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment