Created
May 9, 2017 10:04
-
-
Save jordinebot/ff34f9f23cfd6c736536917064ce6927 to your computer and use it in GitHub Desktop.
ES6 Ajax Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState */ | |
const UNSENT = 0, | |
OPENED = 1, | |
HEADERS_RECEIVED = 2, | |
LOADING = 3, | |
DONE = 4; | |
/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Status */ | |
const OK = 200; | |
class ReadyStates { | |
static get UNSENT() { | |
return UNSENT; | |
} | |
static get OPENED() { | |
return OPENED; | |
} | |
static get HEADERS_RECEIVED() { | |
return HEADERS_RECEIVED; | |
} | |
static get LOADING() { | |
return LOADING; | |
} | |
static get DONE() { | |
return DONE; | |
} | |
} | |
class HTTPStatus { | |
static get OK() { | |
return OK; | |
} | |
} | |
export class Ajax { | |
constructor() { | |
this.xhr = new XMLHttpRequest(); | |
} | |
onStateChangedEvent(xhr, onSuccess, onError) { | |
return () => { | |
if (xhr.readyState === ReadyStates.DONE && xhr.status === HTTPStatus.OK) { | |
let contentType = xhr.getResponseHeader("Content-Type").toLowerCase(); | |
if (contentType === 'application/json') { | |
onSuccess(JSON.parse(xhr.responseText), contentType); | |
} else { | |
onSuccess(xhr.responseText, contentType); | |
} | |
} else if (xhr.readyState === ReadyStates.DONE && xhr.status !== HTTPStatus.OK) { | |
onError(xhr.responseText, xhr.status); | |
} | |
} | |
} | |
encodeData(data) { | |
return Object.keys(data).map((key) => { | |
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]); | |
}).join('&'); | |
} | |
get(endpoint, data, onSuccess, onError) { | |
let xhr = this.xhr; | |
xhr.open('GET', endpoint + '?' + this.encodeData(data)); | |
xhr.onreadystatechange = this.onStateChangedEvent(xhr, onSuccess, onError); | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.send(); | |
return xhr; | |
} | |
post(endpoint, data, onSuccess, onError) { | |
let xhr = this.xhr; | |
xhr.open('POST', endpoint, true); | |
xhr.onreadystatechange = this.onStateChangedEvent(xhr, onSuccess, onError); | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); | |
xhr.send(this.encodeData(data)); | |
return xhr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment