ajax.js 1.48 KB
class Ajax {

    constructor(object){
	if (typeof object !== "object")
		this.data = {};
	else
		this.data = object;
		
        this.http = new XMLHttpRequest();
    }

    default(){
        if (("url" in this.data) === false) {
		throw "URL not set";
	}
        if (("async" in this.data) === false){
		this.data.async = true;
	}
        if ( "success" in this.data ){
		this.http.onload = () => {
			if (this.http.status == 200)
				this.data.success(this.http.response);
		}
	}
        if ( "error" in this.data ){
		this.http.onerror = () => this.data.error(this.http.response);
	}
        if (this.data.async === false && "timeout" in this.data){

            this.http.timeout = this.data.timeout;
	    if ("ontimeout" in this.data)
	    	this.http.ontimeout = (this.data.ontimeout).bind(this.http);
        }
    }

    post(){
        this.default();
        this.http.open("POST", this.data.url, this.data.async);
	if ("contentType" in this.data) {
		this.http.setRequestHeader('Content-Type', this.data.contentType);
	}

	if ("data" in this.data) {
		this.http.send(JSON.stringify(this.data.data));
	}
	else {
		this.http.send();
	}
    }
        
    get(){
        this.default();
	if ("contentType" in this.data) {
		this.http.setRequestHeader('Content-Type', this.data.contentType);
	}

	if ("data" in this.data) {
		this.http.open("GET", this.data.url + "?" + this.data.data, this.data.async);
	}
	else {
		this.http.open("GET", this.data.url, this.data.async);
	}
        this.http.send();
    }
}