User:JackSchmidt/JS Ajax.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:JackSchmidt/JS Ajax. |
// 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) { }
};