Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  30] [ 6]  / answers: 1 / hits: 52657  / 12 Years ago, sun, november 11, 2012, 12:00:00

I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:



<IFRAME SRC=kgr.bss ID=myframe onLoad=readFile();> </IFRAME>


and (with file_inhoud, lines defined elsewhere)



function readFile() {
func=readFile=;
debug2(0);
var x=document.getElementById(myframe);
debug2(1);
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2(1a+doc);
var file_inhoud=doc.document.body;
debug2(2:);
lines = file_inhoud.split(n);
debug2(3);
fileloaded();
debug2(4);
}


Debug function shows:



readFile=0//readFile=1//readFile=1a[object HTMLDocument]//


So statement that stops the program is:



var file_inhoud=doc.document.body;


What is wrong? What is correct (or best) way to read this file?



Note: I see that the file is read and displayed in the frame.



Thanks!


More From » file

 Answers
25

The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:



var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject(Microsoft.XMLHTTP);
}

xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open(GET,kgr.bss); //assuming kgr.bss is plaintext
xhr.send();


The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.


[#82053] Friday, November 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julieth

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;