Read data in HTML object tag

半城伤御伤魂 提交于 2019-12-21 04:56:15

问题


I have a text file stored on the server and an object in HTML like this:

<object id="data" type="text/plain" data="test.txt"></object>

How can I read the contents of test.txt in Javascript? What I have so far is:

var data = document.getElementByID("data");

But I can't figure out how to read the HTML document inside the object tag.


回答1:


The object tag has to make a separate request to the server and then load that content. Meanwhile, your JavaScript has already executed and "misses the bus."

Run your code inside the onload event of the object.

Then use .contentDocument.body.childNodes[0].innerHTML to view the text file.

var object = document.getElementByID("data");
object.onload = function() {
    var data = object.contentDocument.body.childNodes[0].innerHTML;
    // use the data
};



回答2:


I created a simple function and button as an example. Just copy the html and js code and it should work for you. Just make sure you create the appropriate txt or html file for the object to import.

function getObjectData()
{
    //alert("getObjectData");
    
    var myData = "";
    var object = document.getElementById("data");
    
    //get data inside object data
    var myData = object.contentDocument.body.childNodes[0].innerHTML;

    alert("myData => " + myData + " <= myData" );
}
#data{
    height: 36px;
    border: solid 1px red;
    /*overflow: hidden;*/
}
<div class="main">
    <object id="data" type="text/plain" data="test.txt"></object>
</div>
<br />
<button onclick="getObjectData()">Get Object Data</button>


来源:https://stackoverflow.com/questions/36659202/read-data-in-html-object-tag

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