Skip to content

Instantly share code, notes, and snippets.

@mrfratello
Last active August 13, 2016 09:07
Show Gist options
  • Save mrfratello/c1a48d5646fe7641fff84abef0e0ecd5 to your computer and use it in GitHub Desktop.
Save mrfratello/c1a48d5646fe7641fff84abef0e0ecd5 to your computer and use it in GitHub Desktop.
AJAX on pure JS
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function doAjax(url, method, params) {
var ajax = getXmlHttp();
ajax.open(method, url, true);
ajax.setRequestHeader("Content-type", "application/json; charset=utf-8");
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if(ajax.status == 200) {
console.log( ajax.responseText );
// if JSON in responce
// console.log( JSON.parse( ajax.responseText ) );
} else {
alert('Ошибка связи с сервером');
}
}
};
ajax.send(params);
}
// example to use
var url = "path/to/backend/handler",
method = "POST",
params = {
"param1": 'value1',
"param2": 'value2'
}
doAjax(url, method, params);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment