I have a file foo.txt with the following rows:
row1
row2
row3
I would like to create a link to this file in my HTML and to read it with Javascript on client-side. Is there a solution for this?
I have a file foo.txt with the following rows:
row1
row2
row3
I would like to create a link to this file in my HTML and to read it with Javascript on client-side. Is there a solution for this?
if the file is on your server you can use the following:
jQuery.get('your_file.txt',function(data){
alert(data);
});
If you want to pull in from your local system you'll need an upload mechanism in place first.
Update:
Do it synchronously:
$.ajax({
url: "your_file.txt",
async: false,
success: function(data){ alert(data); }
});
File Not on your own server:
That is not possible with client-side JavaScript due to security reasons. Imagine you are trying to access the file system of the client.
Though there is option of File System Object in Internet Explorer but yet it is generally not a good idea to do I/O on client machine unless there is no purpose to harm it.
File on your server:
If however you meant to read a file from your own domain/space, you can use AJAX as @Fluidbyte pointed out.
You can also use File API of html5 in browsers that support it.
You could use the File API for supported browsers.
If not, use the traditional "upload to server and read from server" approach. This can be done in AJAX as well.
I would suggest you store the file in HTML5 Localstorage in the Clients browser since it is rows you could save it in a simple loop as
localStorage.setItem("key1", "value1");
localStorage["key1"] = "value1";
...
write a serversided script that reads it line by line and outputs javascript code.
then later to read it you simply need to :
function listAllItems(){
for (i=0; i<=localStorage.length-1; i++)
{
key = localStorage.key(i);
val = localStorage.getItem(key);
}
}
Each website usually gets 5MB of Localstorage space. You can write a function to update the Localstorage append something to it and send it back to the server if needed, etc.
var oFReader = new FileReader();
oFReader.readAsText(document.getElementById("fileImportOrExport").files[0]);
oFReader.onload = function (oFREvent) {
var fileImportOrExportContent = oFREvent.target.result;
}
oFReader.onerror = function (OFREvent) {
alert("Error in reading");
}