Loading a remote file in JavaScript
Next up on my list of things I don’t know how to do is load a file in JavaScript. For now, let’s assume the file is hosted on the same server as the script. I understand that reading local files requires HTML5 and reading files from other servers can be troublesome.
jQuery has several ways to retrieve file contents: load, ajax, and get. The latter two let you specify the file type, which I found to be important. If I tried to load a JavaScript file, jQuery would automatically execute it. For my purposes, I wanted the file as plain text, which the get function lets me specify.
Here’s a test script I ended up with:
/** Callback for when jQuery has my file loaded. Places the content in the filecontents div. @param data File contents */ function handleFile(data) { jQuery('#filecontents').html(data); } // Issue a request to load test_file as text (don't eval it, jQuery!). jQuery.get('https://twodee.org/scripts/sandbox/test_file', handleFile, 'text'); document.write('<div id="filecontents"></div>');
When I execute it, the file is properly embedded:
jQuery’s fun.