Skip to content

Instantly share code, notes, and snippets.

@inter-coder
Created March 15, 2016 22:14
Show Gist options
  • Save inter-coder/5296e266f76b62dd7693 to your computer and use it in GitHub Desktop.
Save inter-coder/5296e266f76b62dd7693 to your computer and use it in GitHub Desktop.
Ajax for loading documents from local and crossdomain
var ajax_get = function(p) {
var cors = false;
if (p.url.split("//").length == 1) {
var url = p.url + "?" + this.timeStamp();
} else {
cors = true;
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html WHERE url="' + p.url + '" AND xpath="//body"') + '&format=xml&callback=cb';
}
return new Promise(function(resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
if (this.status == 200) {
function cb(d) {
return d;
}
if (cors) {
var pom = document.createElement("template");
pom.innerHTML = eval(this.responseText).results[0];
for (var i = 0; i < pom.content.childNodes.length; i++) {
if (pom.content.childNodes[i].tagName != undefined) {
var dom = pom.content.childNodes[i].querySelectorAll("[src]");
for (var x = 0; x < dom.length; x++) {
if (dom[x].getAttribute("src").split("//").length == 1) {
dom[x].src = p.url + "/" + dom[x].getAttribute("src");
}
};
var dom = pom.content.childNodes[i].querySelectorAll("[href]");
for (var x = 0; x < dom.length; x++) {
if (dom[x].getAttribute("href").split("//").length == 1) {
dom[x].href = p.url + "/" + dom[x].getAttribute("href");
}
}
}
};
resolve(pom.innerHTML);
} else {
resolve(this.responseText);
}
} else {
reject(Error(this.statusText));
}
};
xhttp.onerror = function() {
reject(Error("Network Error"));
};
xhttp.open("GET", url, true);
xhttp.send();
}).then(function(response) {
p.callBack(response);
}, function(error) {
console.error("Fail! But u promise :(");
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment