You can use the XMLHttpRequest
to load a text file. In the example below the DIV
named dummy
will receive the loaded text. But instead you could also place the http.responseText
into a var for further processing.
<div id="test">dummy</div>
<input id="reset" type="button" value="reset" onMouseUp="resetDIV()" />
<input id="load" type="button" value="load unsafe" onMouseUp="httpRequest('http://yourserver/yourpath/hello.txt')" />
<input id="load" type="button" value="load safer" onMouseUp="httpRequestByID(1)" />
const test = document.getElementById('test');
const http = new XMLHttpRequest();
function resetDIV() {
test.innerHTML = 'dummy';
}
const httpResult = function() {
console.log(http);
test.innerHTML = http.responseText;
}
function httpRequest(_url) {
// hacker unsafe because if a hacker finds a way to add or modify an element in the DOM and call your function with his own injected URL he can look for files you don't want others to see.
http.open('GET', _url);
http.onloadend = httpResult;
http.send();
}
function httpRequestByID(_fileNum) {
// a little safer function it is when the urls are hard typed and you can only reference by a file number
if((typeof _fileNum)=='number' && _fileNum>0 && _fileNum<3){
if(_fileNum===1){http.open('GET', 'http://yourserver/yourpath/hello.txt');}
if(_fileNum===2){http.open('GET', 'http://yourserver/yourpath/other.txt');}
http.onloadend = httpResult;
http.send();
}else{
alert('httpRequestByID received an invalid argument');
// nothing more should happen
}
}