Created
March 7, 2016 11:52
-
-
Save hsnaydd/0d6061a8801222ccf0e6 to your computer and use it in GitHub Desktop.
Es6 Ajax request
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
export default class Ajax { | |
get(url, callback) { | |
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); | |
xhr.open('GET', url); | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState > 3 && xhr.status === 200) { | |
callback(xhr.responseText); | |
} | |
}; | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.send(); | |
return xhr; | |
} | |
post(url, data, callback) { | |
let params = typeof data == 'string' ? data : Object.keys(data).map((k) => { | |
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]); | |
}).join('&'); | |
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); | |
xhr.open('POST', url); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState > 3 && xhr.status === 200) { | |
callback(xhr.responseText); | |
} | |
}; | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
xhr.send(params); | |
return xhr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hey! I think it would be nice if you'd use promises aswell :)