简体   繁体   English

如何将 .txt 文件中的数据插入 html

[英]How to insert the data from a .txt file into a html

I would like to insert the data from a text file into a html.我想将文本文件中的数据插入到 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";

You can use JavaScript and the XMLHttpRequest object.您可以使用JavaScriptXMLHttpRequest对象。

Something like this:像这样的东西:

Declare your XHR function:声明你的 XHR 函数:

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 .在此处找到有关XMLHttpRequest对象的更多信息。

About innerHTML , here .关于innerHTML请看这里

You need to "read" the file first, if you are using Jquery, you can do:您需要先“读取”文件,如果您使用的是 Jquery,则可以执行以下操作:

$.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:您当前的代码只会打印bestreads/books/alannathefirstadventure/description.txt要将文本文件中的内容打印到您的 html div,您需要读取该文件,将其数据放入一个变量中并将该变量分配给您的 div src 像下面的代码:

$.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.在上面的代码中, data将包含来自指定文本文件的全部内容。 Please verify location of text file as its a common mistake programmers make.请验证文本文件的位置,因为这是程序员常犯的错误。

It might be worth mentioning a pure html way of doing this with object tag可能值得一提的是使用对象标记执行此操作的纯 html 方式

you should be able to do你应该能够做到

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

However, css won't apply to the text.但是,css 不适用于文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM