Jeroen
Jeroen

Reputation: 31

Read csv file with javascript

Currently im using this code to view content of a csv in a webbrowser with javascript. But this only works in firefox as other browser dont allow you to grab content from an iframe. I need to convert my csv to a txt if i want to use this method, and would like to keep csv instead of txt.

Do any of you know how I can make this work without the Iframe part and txt part so I can use it in different browser? Thanks!

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

<script>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");
var alltext = "";

if(arrLines[12].split(";")[8] == "0"){ }
for (var i = 1; i < arrLines.length; i++)
{
    alltext += "<tr>";
    var prop = arrLines[i].split(";");
    for (var j = 0; j < 11; j++) {
        alltext += "<td>" + prop[j] + "</td>";
    }
    alltext += "</tr>";
    document.close();
}
document.getElementById("message").innerHTML = alltext;
}
</script>

Upvotes: 0

Views: 348

Answers (1)

WuDo
WuDo

Reputation: 195

I would suggest Ajax get of the file -> that way you can get the text content.

<!-- no iframe -->

<script>
var url = "http://www.example.com/file.txt";
var txtFile = new XMLHttpRequest();
txtFile.open("GET",url,true);
txtFile.send();

txtFile.onreadystatechange = function(){
     if (txtFile.readyState== 4 && txtFile.status == 200)
     {              
         var strRawContents = jsonFile.responseText;
     }
}
</script>

Upvotes: 1

Related Questions