When attempting to implement a simple text file reader using XMLHttpRequest, it may not function properly. This article explores potential issues and provides solutions to rectify them.
When an XMLHttpRequest request is made with a local file path, it may result in an Exception 101. This occurs because modern browsers strictly restrict direct file system access. To circumvent this, avoid using file:/// paths.
A more modern and user-friendly approach to retrieving data from URLs is the Fetch API, introduced in JS. The following code demonstrates its usage:
fetch("myText.txt") .then((res) => res.text()) .then((text) => { // Process the text }) .catch((e) => console.error(e));
For local file requests using XMLHttpRequest, it's necessary to check both status 0 and 200 because the status is not returned from a web server:
function readTextFile(file) { var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); rawFile.onreadystatechange = function () { if(rawFile.readyState === 4) { if(rawFile.status === 200 || rawFile.status == 0) { var allText = rawFile.responseText; console.log(allText); } } } rawFile.send(null); }
When using XMLHttpRequest with local files, it's imperative to specify the file:// protocol in the filename:
readTextFile("file:///C:/your/path/to/file.txt");
The above is the detailed content of How Can I Read a Local Text File in a Web Browser?. For more information, please follow other related articles on the PHP Chinese website!