User:JackSchmidt/JS Ajax.js

// Basic AJAX code for wikipedia

// (c) 2007 Jack Schmidt, available under GPL, BSD, or CC-SA

// Obviously this just calls api.php and index.php with arguments. // Since index.php?action=ajax requires repeated arguments, you can // give a key=value argument in [ key, value ] form, not just { key: value } // form.

function JS_PHP( php, args, id, callback ) { var http; var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/' + php; for ( var k in args ) { if( typeof args[k] == typeof [] ) { url += ((url.indexOf("?")==-1)?"?":"&") + encodeURIComponent( args[k][0] ) + "=" + encodeURIComponent( args[k][1] ); } else url += ((url.indexOf("?")==-1)?"?":"&") + encodeURIComponent( k ) + "=" + encodeURIComponent( args[k] ); } http = sajax_init_object; http.open( 'GET', url, true ); http.onreadystatechange = function { return JS_Callback( http, id, callback ); } http.send( null ); } function JS_API( args, id, callback ) { return JS_PHP( 'api.php', args, id, callback ); } function JS_INDEX( args, id, callback ) { return JS_PHP( 'index.php', args, id, callback ); } function JS_QUERY( args, id, callback ) { return JS_PHP( 'query.php', args, id, callback ); } function JS_Callback( http, id, callback ) { if ( !http ) return; if ( http.readyState != 4) return; if ( http.status != 200 ) return; try { callback( id, http.responseXML ? http.responseXML : http.responseText ); } catch (e) { } };