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
4 Answers
Reset to default 2You 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744345209a4569642.html
评论列表(0条)