最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to insert the data from a .txt file into a html - Stack Overflow

programmeradmin2浏览0评论

I would like to insert the data from a text file into a html. How can I do that? Is there something wrong in my code. That only thing I know is the path of the text file. Thanks.

document.getElementById("description").src =  "/bestreads/books/alannathefirstadventure/description.txt";

I would like to insert the data from a text file into a html. How can I do that? Is there something wrong in my code. That only thing I know is the path of the text file. Thanks.

document.getElementById("description").src =  "/bestreads/books/alannathefirstadventure/description.txt";
Share Improve this question edited May 20, 2017 at 5:08 li x 4,0612 gold badges34 silver badges52 bronze badges asked May 20, 2017 at 4:21 TakTak 1671 gold badge6 silver badges18 bronze badges 1
  • Possible duplicate of Display text from local text file into a div? (No webserver) – jarvo69 Commented May 20, 2017 at 5:22
Add a ment  | 

4 Answers 4

Reset to default 2

You can use JavaScript and the XMLHttpRequest object.

Something like this:

Declare your XHR function:

function sendXHR(type, url, data, callback) {
  var newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(type, url, true);
  newXHR.send(data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response);
    }
  };
}

Then you can use:

sendXHR("GET", "/bestreads/books/alannathefirstadventure/description.txt", null, function(response) { // response contains the content of the description.txt file.
  document.getElementById("description").innerHTML = response; // Use innerHTML to get or set the html content.
});

Please, you can find more information about XMLHttpRequest object, here.

About innerHTML, here.

You need to "read" the file first, if you are using Jquery, you can do:

$.get("bestreads/books/alannathefirstadventure/description.txt", function(data) {
     document.getElementById("description").src=data;
});

Your current code will just print bestreads/books/alannathefirstadventure/description.txt .To print the content from the text file to your html div, you will need to read the file, get its data in a variable and assign that variable to your div's src like below code:

$.get("bestreads/books/alannathefirstadventure/description.txt", function(data) {
     document.getElementById("description").src=data;
});

In above code, data will have entire content from the specified text file. Please verify location of text file as its a mon mistake programmers make.

It might be worth mentioning a pure html way of doing this with object tag

you should be able to do

<div><object data="/bestreads/books/alannathefirstadventure/description.txt"></object></div>

However, css won't apply to the text.

发布评论

评论列表(0)

  1. 暂无评论