我想将文本文件中的数据插入到html中。我怎样才能做到这一点?我的代码中有什么问题。我唯一知道的是文本文件的路径。感谢。
document.getElementById("description").src = "/bestreads/books/alannathefirstadventure/description.txt";
答案 0 :(得分:2)
您可以使用 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
对象here。
关于innerHTML
,here。
答案 1 :(得分:1)
你需要"阅读"首先是文件,如果你使用的是Jquery,你可以这样做:
$.get("bestreads/books/alannathefirstadventure/description.txt", function(data) {
document.getElementById("description").src=data;
});
答案 2 :(得分:1)
您当前的代码只会打印 bestreads / books / alannathefirstadventure / description.txt 。要将文本文件中的内容打印到您的html div,您需要阅读该文件,获取其数据在变量中并将该变量分配给div的src,如下面的代码:
$.get("bestreads/books/alannathefirstadventure/description.txt", function(data) {
document.getElementById("description").src=data;
});
在上面的代码中,data
将包含指定文本文件中的全部内容。
请验证文本文件的位置是程序员常犯的错误。
答案 3 :(得分:1)
值得一提的是使用object tag
执行此操作的纯html方法你应该可以做到
<div><object data="/bestreads/books/alannathefirstadventure/description.txt"></object></div>
但是,css不适用于该文本。