2 * xhr.js - XMLHttpRequest helper class
3 * (c) 2008-2010 Jo-Philipp Wich
8 this.reinit = function()
10 if( window.XMLHttpRequest ) {
11 this._xmlHttp = new XMLHttpRequest();
13 else if( window.ActiveXObject ) {
14 this._xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
17 alert("xhr.js: XMLHttpRequest is not supported by this browser!");
21 this.busy = function() {
22 switch( this._xmlHttp.readyState )
34 this.abort = function() {
36 this._xmlHttp.abort();
39 this.get = function(url,data,callback)
43 var xhr = this._xmlHttp;
44 var code = this._encode( data );
46 url = location.protocol + '//' + location.host + url;
49 if( url.substr(url.length-1,1) == '&' )
54 xhr.open( 'GET', url, true );
56 xhr.onreadystatechange = function()
58 if( xhr.readyState == 4 ) {
60 if( xhr.getResponseHeader("Content-Type") == "application/json" ) {
62 json = eval('(' + xhr.responseText + ')');
69 callback( xhr, json );
76 this.post = function(url,data,callback)
80 var xhr = this._xmlHttp;
81 var code = this._encode( data );
83 xhr.onreadystatechange = function()
85 if( xhr.readyState == 4 )
89 xhr.open( 'POST', url, true );
90 xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
91 xhr.setRequestHeader( 'Content-length', code.length );
92 xhr.setRequestHeader( 'Connection', 'close' );
96 this.cancel = function()
98 this._xmlHttp.onreadystatechange = function(){};
99 this._xmlHttp.abort();
102 this.send_form = function(form,callback,extra_values)
106 for( var i = 0; i < form.elements.length; i++ )
108 var e = form.elements[i];
112 code += ( code ? '&' : '' ) +
113 form.elements[i].name + '=' + encodeURIComponent(
114 e.options[e.selectedIndex].value
119 for( var j = 0; j < e.length; j++ )
121 code += ( code ? '&' : '' ) +
122 e[j].name + '=' + encodeURIComponent( e[j].value );
127 code += ( code ? '&' : '' ) +
128 e.name + '=' + encodeURIComponent( e.value );
132 if( typeof extra_values == 'object' )
133 for( var key in extra_values )
134 code += ( code ? '&' : '' ) +
135 key + '=' + encodeURIComponent( extra_values[key] );
138 ( form.method == 'get' )
139 ? this.get( form.getAttribute('action'), code, callback )
140 : this.post( form.getAttribute('action'), code, callback )
144 this._encode = function(obj)
146 obj = obj ? obj : { };
147 obj['_'] = Math.random();
149 if( typeof obj == 'object' )
155 code += ( code ? '&' : '' ) +
156 k + '=' + encodeURIComponent( obj[k] );