I have an external textfile of variable length named profiles.txt with information in the following format:
Jason/Red/Tyrannosaurus
Zack/Black/Mastodon
Billy/Blue/Triceratops
Trini/Yellow/Griffin
(etc)
How can I read through the file using JavaScript to output the following HTML:
Name: Jason<br>
Color: Red<br>
Avatar: Tyrannosaurus<br>
<br>
Name: Zack<br>
Color: Black<br>
Avatar: Mastodon<br>
<br>
(etc)
-
Where is the JavaScript running? From the browser?David Wolever– David Wolever2011年09月13日 17:52:21 +00:00Commented Sep 13, 2011 at 17:52
-
javascript on the browser, external file is .txt file located on the same domain as the .html and javascript filesHenry Yun– Henry Yun2011年09月13日 18:12:41 +00:00Commented Sep 13, 2011 at 18:12
4 Answers 4
Here's an example using XMLHttpRequest:
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET', "test.txt", false);
xmlhttp.send();
document.write(xmlhttp.responseText.split('\r\n').map(function (i) {return i.replace(/(.+),(.+),(.+)/g, 'Name: 1ドル<br>Color: 2ドル<br>Avatar: 3ドル<br>')} ).join('<br/>'));
Array.map needs to be shim in IE8 and below. Also, IE uses new ActiveXObject("Msxml2.XMLHTTP")
This is a very slimmed down example. I'm using asyc false which is bad and document.write which is bad. But I just wanted to demonstrate getting the file and parsing the input.
4 Comments
ONLY APPLIES IF THE FILE IS NOT ALREADY ON THE SERVER (not specified in question)
Without posting the file to the server or pasting the file's contents into a textbox, there is currently no way for javascript to interact directly with the file system.
Also for security reasons, javascript may not, by itself, look at the contents of a file that has been selected using a file-type input.
So, your options are:
- Upload the file to the server using AJAX-style form post, return the contents (jQuery plugin for AJAX file uploads)
- Submit the file via normal form postback, when the page is reloaded you can pass the contents along to javascript with JSON written to the output
- Copy/paste the data into a textarea, use an onKeyUp event to detect entry of data (or add a "Process" button) to read the textarea contents and go from there (sample)
Comments
There is no file I/O in javascript for security reasons. Your best bet is to expose this text file in your server code and make an ajax call for it from the javascript
Comments
var fileRead = "Jason,Red,Tyrannosaurus\nZack,Black,Mastodon\nBilly,Blue,Triceratops\nTrini,Yellow,Griffin";
var lines = fileRead.split("\n");
for (var i in lines){
var pdata = lines[i].split(",");
jQuery("#ResultDiv").append("Name: " + pdata[0] + "<br/>Color: " + pdata[1] + "<br/>Avatar: " + pdata[2] + "<br/><br/>" );
}