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 = 'http://' + 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 ) {
67 this.post = function(url,data,callback)
71 var xhr = this._xmlHttp;
72 var code = this._encode( data );
74 xhr.onreadystatechange = function()
76 if( xhr.readyState == 4 )
80 xhr.open( 'POST', url, true );
81 xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
82 xhr.setRequestHeader( 'Content-length', code.length );
83 xhr.setRequestHeader( 'Connection', 'close' );
87 this.cancel = function()
89 this._xmlHttp.onreadystatechange = function(){};
90 this._xmlHttp.abort();
93 this.send_form = function(form,callback,extra_values)
97 for( var i = 0; i < form.elements.length; i++ )
99 var e = form.elements[i];
103 code += ( code ? '&' : '' ) +
104 form.elements[i].name + '=' + encodeURIComponent(
105 e.options[e.selectedIndex].value
110 for( var j = 0; j < e.length; j++ )
112 code += ( code ? '&' : '' ) +
113 e[j].name + '=' + encodeURIComponent( e[j].value );
118 code += ( code ? '&' : '' ) +
119 e.name + '=' + encodeURIComponent( e.value );
123 if( typeof extra_values == 'object' )
124 for( var key in extra_values )
125 code += ( code ? '&' : '' ) +
126 key + '=' + encodeURIComponent( extra_values[key] );
129 ( form.method == 'get' )
130 ? this.get( form.getAttribute('action'), code, callback )
131 : this.post( form.getAttribute('action'), code, callback )
135 this._encode = function(obj)
137 if( typeof obj == 'object' )
143 code += ( code ? '&' : '' ) +
144 k + '=' + encodeURIComponent( obj[k] );