Skip to content

Instantly share code, notes, and snippets.

@omichelsen
Created January 16, 2014 22:45
Show Gist options
  • Save omichelsen/8464951 to your computer and use it in GitHub Desktop.
Save omichelsen/8464951 to your computer and use it in GitHub Desktop.
JavaScript async remote
(function (window, document) {
var settings = {
dataId: 'data-myModule-id',
url: '/api/mymodule/'
};
function load() {
var elems = document.querySelectorAll('[' + settings.dataId + ']');
if (!elems) {
return;
}
for (var i = 0; i < elems.length; i++) {
var target = elems[i],
id = target.getAttribute(settings.dataId);
if (!id) {
continue;
}
get(settings.url + id, function (response) {
if (!response.harTilmelding) {
return;
}
var btn = document.createElement('button'),
txt = document.createTextNode(response.tekst);
btn.appendChild(txt);
btn.onclick = function () {
location.href = response.url;
};
target.appendChild(btn);
});
}
}
function get(url, success) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
success(JSON.parse(xmlhttp.responseText));
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
window.onload = load;
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment