Created
March 15, 2016 22:14
-
-
Save inter-coder/5296e266f76b62dd7693 to your computer and use it in GitHub Desktop.
Ajax for loading documents from local and crossdomain
This file contains 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
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