Posted By

Twain on 10/28/07


Tagged

web


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

robotoverlord
vali29
wirenaught


Read local file with XmlHttpRequest


 / Published in: JavaScript
 

For a locally saved web app, this is a cross-browser way to read files (writing not implemented).

  1. /* Read a file using xmlhttprequest
  2.  
  3. If the HTML file with your javascript app has been saved to disk,
  4. this is an easy way to read in a data file. Writing out is
  5. more complicated and requires either an ActiveX object (IE)
  6. or XPCOM (Mozilla).
  7.  
  8. fname - relative path to the file
  9. callback - function to call with file text
  10. */
  11. function readFileHttp(fname, callback) {
  12. xmlhttp = getXmlHttp();
  13. xmlhttp.onreadystatechange = function() {
  14. if (xmlhttp.readyState==4) {
  15. callback(xmlhttp.responseText);
  16. }
  17. }
  18. xmlhttp.open("GET", fname, true);
  19. xmlhttp.send(null);
  20. }
  21.  
  22. /*
  23. Return a cross-browser xmlhttp request object
  24. */
  25. function getXmlHttp() {
  26. if (window.XMLHttpRequest) {
  27. xmlhttp=new XMLHttpRequest();
  28. } else if (window.ActiveXObject) {
  29. xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  30. }
  31. if (xmlhttp == null) {
  32. alert("Your browser does not support XMLHTTP.");
  33. }
  34. return xmlhttp;
  35. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: syockit on February 23, 2009

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.

Posted By: kjurka on April 1, 2009

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); } }

Posted By: Twain on June 29, 2009

Thank you kjurka, I have updated the snippet to check readyState....

Posted By: Pfhortipfhy on July 22, 2009

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?

You need to login to post a comment.