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 || location.hostname) +
47 ( location.port ? ':' + location.port : '' ) + url;
50 if( url.substr(url.length-1,1) == '&' )
55 xhr.open( 'GET', url, true );
57 xhr.onreadystatechange = function()
59 if( xhr.readyState == 4 ) {
61 if( xhr.getResponseHeader("Content-Type") == "application/json" ) {
63 json = eval('(' + xhr.responseText + ')');
70 callback( xhr, json );
77 this.post = function(url,data,callback)
81 var xhr = this._xmlHttp;
82 var code = this._encode( data );
84 xhr.onreadystatechange = function()
86 if( xhr.readyState == 4 )
90 xhr.open( 'POST', url, true );
91 xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
92 xhr.setRequestHeader( 'Content-length', code.length );
93 xhr.setRequestHeader( 'Connection', 'close' );
97 this.cancel = function()
99 this._xmlHttp.onreadystatechange = function(){};
100 this._xmlHttp.abort();
103 this.send_form = function(form,callback,extra_values)
107 for( var i = 0; i < form.elements.length; i++ )
109 var e = form.elements[i];
113 code += ( code ? '&' : '' ) +
114 form.elements[i].name + '=' + encodeURIComponent(
115 e.options[e.selectedIndex].value
120 for( var j = 0; j < e.length; j++ )
122 code += ( code ? '&' : '' ) +
123 e[j].name + '=' + encodeURIComponent( e[j].value );
128 code += ( code ? '&' : '' ) +
129 e.name + '=' + encodeURIComponent( e.value );
133 if( typeof extra_values == 'object' )
134 for( var key in extra_values )
135 code += ( code ? '&' : '' ) +
136 key + '=' + encodeURIComponent( extra_values[key] );
139 ( form.method == 'get' )
140 ? this.get( form.getAttribute('action'), code, callback )
141 : this.post( form.getAttribute('action'), code, callback )
145 this._encode = function(obj)
147 obj = obj ? obj : { };
148 obj['_'] = Math.random();
150 if( typeof obj == 'object' )
156 code += ( code ? '&' : '' ) +
157 k + '=' + encodeURIComponent( obj[k] );