/ Published in: JavaScript
For a locally saved web app, this is a cross-browser way to read files (writing not implemented).
Expand |
Embed | Plain Text
/* Read a file using xmlhttprequest If the HTML file with your javascript app has been saved to disk, this is an easy way to read in a data file. Writing out is more complicated and requires either an ActiveX object (IE) or XPCOM (Mozilla). fname - relative path to the file callback - function to call with file text */ function readFileHttp(fname, callback) { xmlhttp = getXmlHttp(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4) { callback(xmlhttp.responseText); } } xmlhttp.open("GET", fname, true); xmlhttp.send(null); } /* Return a cross-browser xmlhttp request object */ function getXmlHttp() { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp == null) { alert("Your browser does not support XMLHTTP."); } return xmlhttp; }
Comments
Subscribe to comments
You need to login to post a comment.

I know this post is kind of old, but just to inform you that I tried this on Firefox 3.0.6 and it didn't work. Or did you mean on locally served pages? It doesn't work on file:// protocol.
This does work locally for me on FF 3.0.8. The filename is supposed to be relative to the currently loaded page, so you shouldn't be messing with the file:// protocol prefix.
I also found that the onreadystatechange callback function should test the readyState variable otherwise your function gets called for each state change rather than just when it has completed loading the file.
xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4) { callback(xmlhttp.responseText); } }
Thank you kjurka, I have updated the snippet to check readyState....
I was unable to get this to work in Safari version 4.0.1 (I get error code 0 for the status). It worked fine in Firefox, though. Is anyone else experiencing this?