A sample AJAX implementation.

A sample AJAX implementation.

let AJAX = function(){
    function execute(method, url, data, callback, headers){
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(e){
            //console.log(xhr.readyState);
            if(xhr.readyState==4){
                if(xhr.status == 200)
                callback(xhr.responseText);
            }
        }
        xhr.onerror = function(e){
            console.log('onerror');
        }
        xhr.open(method, url, true);
        if(!headers){
            headers = {'Content-Type': 'application/json;charset=UTF-8'};
        }
        for(let key in headers){
            xhr.setRequestHeader(key, headers[key]);
        }
        console.log(typeof(data));
        switch(typeof(data)){
            case 'function':
                data = data();
                break;
            case 'string':
                //
                break;
            default:
                data = JSON.stringify(data);
        }
        console.log(data);
        xhr.send(data);
    }
    return {
        get: function(url, callback){
            execute('GET', url, null, callback);
        },
        post: function(url, data, callback){
            execute('POST', url, data, callback)
        }
    }
}();

AJAX.get('./data/agents', function(data){
    console.log('GET', data);
});
let data = {name: "GLP", sex: 0, dateOfBirth: "1990-01-01", status: 0};
AJAX.post('./data/agent', data, function(data){
    console.log('POST', data);
});

你可能感兴趣的:(A sample AJAX implementation.)