I would like to make a simple website without cloning HTML files.
I want to store a content in separate text files (or html) in subdirectories (e.g. pages/pagehome.txt, pages/pageabout.txt, pages/pagecontact.txt). I used tag, but it does not allow to reuse css for that embedded content.
I want to import that files to variables and to change divs via innerHTML tag. How can I import content from that files to variables? I don't want to use any complicated APIs or tons of code.
Is there available simply method to load files' content to variables using ONLY JS (No HTML or methods like invisible div with content)?
CodePudding user response:
Use an XMLHttpRequest, and use the onload callback to get the response.
<body>
<div id="divv"></div>
<script>
var txtFile = new XMLHttpRequest();
txtFile.onload = function(e) {
document.getElementById("divv").innerHTML = txtFile.responseText;
}
txtFile.open("GET", "file.txt", true);
txtFile.send(null);
</script>
</body>
EDIT: It seems you need to access local files, so you can use something like this
<body>
<div id="divv"></div>
<script>
window.onload = function() {
var iframe = document.createElement('iframe');
iframe.id = 'iframe';
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = 'file.txt';
iframe.onload = function(){
var text = document.getElementById('iframe').contentDocument.body.firstChild.innerHTML;
document.getElementById('divv').innerHTML = text;
};
}
</script>
</body>
