Access <object> data with JavaScript

余生颓废 提交于 2020-01-24 19:26:07

问题


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:

  1. avoid having to make an XMLHttpRequest;
  2. avoid having text data in the form of a constant in code;
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!