Using Ajax to Read Local Files

AJAX request to local file system not working in Chrome?

Firefox allows the request because it accepts requests to the local file system (ie. the file:// protocol) if they originate from there too. However Chrome denies all XMLHttpRequests to file:// urls.

Note that you cannot make an AJAX request to the local file system from an external domain in either browser - it would be a massive security flaw if you could.

For this AJAX request to work in Chrome you need to make the request to a webserver. If you're on Windows you can easily install IIS or WAMP on your local machine.

Note that it is possible to enable a setting in Google Chrome which allows requests to the local file system from the browser, but it's really not a good idea to use it. If you decide you want to go ahead and do this anyway, a guide can be found here.

Open local files in JavaScript

This is actually most likely a scope issue. Because you're setting allText asynchronously, it's not available immediately after the function returns. In addition, you're reinitializing allText within a function, which messes with the scope of the return regardless.

rawFile.onreadystatechange is executed after the function returns. You can either move the execution into the XHR callback, or wrap the function in a promise, which would still require you modify your control flow a bit.

Move the document.write:

<!DOCTYPE html>
<html>
<script>
function readTextFile(file)
{
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
document.write(allText);
}
}
}
rawFile.send(null);
}

readTextFile("foo.file");

</script>
</html>

Promisified:

function readTextFile( file ) {
return new Promise( function ( fulfill, reject ) {

var allText;
var rawFile = new XMLHttpRequest();
rawFile.open( "GET", file );
rawFile.onreadystatechange = function () {
if ( rawFile.readyState === 4 ) {
if ( rawFile.status === 200 || rawFile.status == 0 ) {
fulfill( rawFile.responseText )
}
}
}
rawFile.send( null );
} );
}
readTextFile( "foo.file" )
.then( function ( t ) {
document.write( t );
} );

Both of these will ensure that your script doesn't attempt to use allText until it's been returned by the XHR request.

Though as Santiago Hernández pointed out, the XHR request is synchronous, and the scope issue was of a different nature than I first assumed. The problem lies in redeclaring the variable within the function, resulting in the one returned to be undefined.

Ajax in Jquery does not work from local file

This is a known problem with Chrome, if you are checking on it. Use XAMPP to run a local webserver, and test your ajax call.

Check this ticket: https://code.google.com/p/chromium/issues/detail?id=40787



Related Topics



Leave a reply



Submit