How to read a text file from server using JavaScript? How to read a text file from server using JavaScript? javascript javascript

How to read a text file from server using JavaScript?


You can use hidden frame, load the file in there and parse its contents.

HTML:

<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>

JavaScript:

<script type="text/javascript">function LoadFile() {    var oFrame = document.getElementById("frmFile");    var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;    while (strRawContents.indexOf("\r") >= 0)        strRawContents = strRawContents.replace("\r", "");    var arrLines = strRawContents.split("\n");    alert("File " + oFrame.src + " has " + arrLines.length + " lines");    for (var i = 0; i < arrLines.length; i++) {        var curLine = arrLines[i];        alert("Line #" + (i + 1) + " is: '" + curLine + "'");    }}</script>

Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.


Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax() function.

<html><head><script src="jquery.js"></script><script>getTxt = function (){  $.ajax({    url:'text.txt',    success: function (data){      //parse your data here      //you can split into lines using data.split('\n')       //an use regex functions to effectively parse it    }  });}</script></head><body>  <button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button></body></html>


You need to use Ajax, which is basically sending a request to the server, then getting a JSON object, which you convert to a JavaScript object.

Check this:

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

If you are using jQuery library, it can be even easier:

http://api.jquery.com/jQuery.ajax/

Having said this, I highly recommend you don't download a file of 3.5MB into JS! It is not a good idea. Do the processing on your server, then return the data after processing. Then if you want to get a new data, send a new Ajax request, process the request on server, then return the new data.

Hope that helps.