Inserting file into html page using Javascript?
I am currently trying to read text from a file and add it to an element in my html page using DOM and Javascript. I am unable to get the text to format. I tried using innerHtml but didn't create it at all (no line breaks).
Here is the javascript:
http = new XMLHttpRequest();
http.open("GET",FILE,false);
http.send();
document.getElementById("tbody").innerHTML = http.responseText
As I said, the text is appended to the tbody element, but not formatted the way it ever was.
I worked with this code (with pre-tag) but as I said it works on my computer but not on the server which doesn't help.
http.open("GET",FILE ,false);
http.send();
var newtext = document.createTextNode(http.responseText);
var para = document.getElementById("tbody");
para.appendChild(newtext);
Here is my javascript code:
getHTTPObject () function {var http = false;
/*@cc_on
@if (@_jscript_version >= 5)
try
{
http = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
http = false;
}
}
@else
{
http = false;
}
@end @*/
if (!http && typeof XMLHttpRequest != 'undefined')
{
try
{
http = new XMLHttpRequest();
}
catch (e)
{
http = false;
}
}
return http
}
function loadData()
{
http = getHTTPObject();
if (http)
{
http.open("GET","my file name",false);
http.send();
var newtext = document.createTextNode(http.responseText);
var para = document.getElementById("tbody");
para.appendChild(newtext);
}
}
source to share
It all depends on what data is in the response. If it is plain text, there is no reason why it should be formatted. If you want html to "respect" whitespace as suggested above, put the text inside the pre-tag.
If the answer is html make sure #tbody is a div or something similar.
You should also learn something like jquery for your DOM manipulation and ajax. This saves you the headaches with cross-browser compatibility and better writing.
source to share
I would argue that the answer is related to your expression: "It works on my PC, but not on the server." I am guessing that you are in trouble because the file does not exist on the server, or the file path is different. have you verified that the file is being sent to your client by trying the file url in the browser directly?