![](/img/trans.png)
[英]How to fetch data in option tags in html from a `.txt` or `.css` file?
[英]How to insert the data from a .txt file into a html
我想将文本文件中的数据插入到 html 中。 我怎样才能做到这一点? 我的代码有问题吗。 我唯一知道的是文本文件的路径。 谢谢。
document.getElementById("description").src = "/bestreads/books/alannathefirstadventure/description.txt";
您可以使用JavaScript和XMLHttpRequest
对象。
像这样的东西:
声明你的 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);
}
};
}
然后你可以使用:
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.
});
请在此处找到有关XMLHttpRequest
对象的更多信息。
关于innerHTML
, 请看这里。
您需要先“读取”文件,如果您使用的是 Jquery,则可以执行以下操作:
$.get("bestreads/books/alannathefirstadventure/description.txt", function(data) {
document.getElementById("description").src=data;
});
您当前的代码只会打印bestreads/books/alannathefirstadventure/description.txt 。要将文本文件中的内容打印到您的 html div,您需要读取该文件,将其数据放入一个变量中并将该变量分配给您的 div src 像下面的代码:
$.get("bestreads/books/alannathefirstadventure/description.txt", function(data) {
document.getElementById("description").src=data;
});
在上面的代码中, data
将包含来自指定文本文件的全部内容。 请验证文本文件的位置,因为这是程序员常犯的错误。
可能值得一提的是使用对象标记执行此操作的纯 html 方式
你应该能够做到
<div><object data="/bestreads/books/alannathefirstadventure/description.txt"></object></div>
但是,css 不适用于文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.