Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created November 11, 2008 14:10
Show Gist options
  • Save atifaziz/23853 to your computer and use it in GitHub Desktop.
Save atifaziz/23853 to your computer and use it in GitHub Desktop.
function JayrockChannel()
{
this.rpc = function(call)
{
var async = typeof(call.callback) === 'function';
var xhr = newXHR();
xhr.open('POST', call.url, async, this.httpUserName, this.httpPassword);
xhr.setRequestHeader('Content-Type', this.contentType || 'application/json; charset=utf-8');
xhr.setRequestHeader('X-JSON-RPC', call.request.method);
if (async) xhr.onreadystatechange = function() { xhr_onreadystatechange(xhr, call.callback); }
xhr.send(JSON.stringify(call.request));
call.handler = xhr;
if (async) return call;
if (xhr.status != 200) throw new Error(xhr.status + ' ' + xhr.statusText);
var response = JSON.eval(xhr.responseText);
if (response.error != null) throw response.error;
return response.result;
}
function xhr_onreadystatechange(sender, callback)
{
if (sender.readyState == /* complete */ 4)
{
try {
sender.onreadystatechange = null; // Avoid IE7 leak (bug #12964)
}
catch (e) {
/* IE 6/Mobile throws for onreadystatechange = null */
}
var response = sender.status == 200 ?
JSON.eval(sender.responseText) : {};
callback(response, sender);
}
}
function newXHR()
{
if (typeof(window) !== 'undefined' && window.XMLHttpRequest)
return new XMLHttpRequest(); /* IE7, Safari 1.2, Mozilla 1.0/Firefox, and Netscape 7 */
else
return new ActiveXObject('Microsoft.XMLHTTP'); /* WSH and IE 5 to IE 6 */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment