I am trying to read a local file from the server. I have been “searching” for a long time about this topic, and some say that this is impossible, while others can do it. During this search, I found this script:
Read the file using xmlhttprequest
If the HTML file with your javascript application was saved to disk, this is an easy way to read in the data file. Writing is more complex and requires either an ActiveX object (IE) or XPCOM (Mozilla).
fname - relative file path
callback - function for calling 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); }
Returns xmlhttp request object with cross browser
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; }
But I don’t know how to use it, and what should the callback function look like? Could you provide some sample code using these functions?
source share