Skip to content

Instantly share code, notes, and snippets.

@bitdivine
Created October 24, 2014 19:14
Show Gist options
  • Save bitdivine/fd4d3a5e14dbe3758f02 to your computer and use it in GitHub Desktop.
Save bitdivine/fd4d3a5e14dbe3758f02 to your computer and use it in GitHub Desktop.
Set HTML element content from URL
function setContentFromUrl(url, container, opt){
console.log("loading", url, "into", container);
opt = opt || {};
var data_filter = opt.filter;
var err_handler = opt.err_handler;
var xhr= new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200){
err_handler(this.status);
return;
}
console.log("Have data");
var data = this.responseText;
if (data_filter){
data = data_filter(data);
}
var tagName = container.tagName.toLowerCase();
switch(tagName){
case "pre":
case "span":
case "div": container.innerText = data; break;
case "textarea": container.value = this.data; break;
default: throw new Error("Unsupported container type: "+tagName);
}
};
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment