We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

Twain on 10/28/07


Tagged

web


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

robotoverlord
vali29


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. callback(xmlhttp.responseText);
  15. }
  16. xmlhttp.open("GET", fname, true);
  17. xmlhttp.send(null);
  18. }
  19.  
  20. /*
  21. Return a cross-browser xmlhttp request object
  22. */
  23. function getXmlHttp() {
  24. if (window.XMLHttpRequest) {
  25. xmlhttp=new XMLHttpRequest();
  26. } else if (window.ActiveXObject) {
  27. xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  28. }
  29. if (xmlhttp == null) {
  30. alert("Your browser does not support XMLHTTP.");
  31. }
  32. return xmlhttp;
  33. }

Report this snippet 

You need to login to post a comment.