问题
I have an <object>
tag like this:
<object id="text" data="file.txt"></object>
And I can get the element like this:
var text = document.getElementById("text");
Now, how do I get the content of the text file?
The purpose of this is to:
- avoid having to make an XMLHttpRequest;
- avoid having text data in the form of a constant in code;
- keep a simple plaintext file in it's original form, without JSON or special formatting, to be accessed by code and become a string variable.
In the same fashion you can have an <img>
or <audio>
tag in the document and then access the image / sound, just for text files.
PS: I'm almost positive the <object>
tag is not the ideal tag for this. This is just as far as I came trying to accomplish what I need.
回答1:
You can load your text file within a hidden iframe and access the contents within that:
<html>
<head>
<script type="text/javascript">
function gettext() {
alert(document.getElementById('ifr').contentDocument.body.innerText);
}
</script>
</head>
<body>
<iframe id="ifr" style="display:none" src="test.txt" onload="gettext()"></iframe>
</body>
</html>
回答2:
I normally prefer AJAX for something like this. Could you do something like this?
var textContent = '';
var textRequest = new XMLHttpRequest();
textRequest.open('GET','file.txt');
textRequest.onreadystatechange = function() {
if (textRquest.readystate == 4 && textRequest.status == 200) {
textContent = textRequest.responseText
}
}
textRequest.send();
Is there a reason you have to use an object element?
来源:https://stackoverflow.com/questions/28420760/access-object-data-with-javascript