Jump to content

User:Anomie/util.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Anomie (talk | contribs) at 04:07, 15 November 2007 (Utility functions). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function jsondecode(v){
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u\n\r\t]/.test(v.replace(/"(\\.|[^"\\])*"/g,''))) && eval('('+v+')');
    } catch(e){
        return null;
    }
}

function api(p, cb){
    var uri=wgServer+wgScriptPath+'/api.php?format=json';
    for(var k in p){
        var v=p[k];
        if(typeof(v)=='object' && (v instanceof Array))
            v=v.map(encodeURIComponent).join('|');
        else
            v=encodeURIComponent(v);
        uri+='&'+encodeURICompoent(k)+'='+v;
    }
    
    var x = sajax_init_object();
    if(!x) return false;
    if(typeof(cb)=='function'){
        x.open('GET', uri, true);
        x.onreadystatechange=function(){
            if(x.readyState!=4) return;
            var r=jsondecode(x.responseText);
            if(!r) throw new Error("Could not parse response");
            cb(r);
        };
        x.send(null);
        return true;
    } else {
        x.open('GET', uri, false);
        x.send(null);
        var r=jsondecode(x.responseText);
        if(!r) throw new Error("Could not parse response");
        return r;
    }
}