Friday, December 17, 2010

How to load text files with jQuery

I was looking into this to help out @tarelli with one of his crazy tasks from hell (spare you the details). Here's how you go about loading local files using jquery:

// LOAD file
$.get('file:///C:/myPath/myFile.txt', function(data) {    
    
    var lines = data.split("\n");

    $.each(lines, function(n, elem) {
       $('#myContainer').append('<div>' + elem + '</div>');
    });
});


This will only work if you double click on the file that executes the script, obviously a web-server shouldn't allow you to go mess around in the file system (I tried on IIS and couldn't fool it, damn). Obviously the same snippet can be used to load files on a web-server by providing a url to an accessible file.

Notes:
  • couldn't get it to work without specifying the file full path in format file:///C:/myPath/myFile.txt
  • to get this to work on chrome you'll have launch it with the --allow-file-access-from-files cmd line arg
P.S. happy xmas