访问特定 URL 以在 JS 中读取文件

Access to particular URL for file reading in JS

本文关键字:读取 文件 JS 以在 URL 访问      更新时间:2023-09-26

我正在尝试读取Java脚本中的文件。我正在使用XAMPP服务器,所有文件都在htdocs文件夹中。但是当我尝试从其他目录读取文件时,它不起作用。

错误:

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
request.send(null);

JavaScript:

<!DOCTYPE html>
<html>
<body>
    <textarea id="box" rows="4" cols="50"> </textarea>

<script>
//get the contents of the text file START   
//Make sure in the JsonData.txt file, after each line there should not be any space ie when you click RIGHT arrow at the end of each line the cursor should go to next line beginning.

            function FileHelper()
            {}
            {
                FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
                {
                    var request = new XMLHttpRequest();
                    request.open("GET", pathOfFileToReadFrom, false);
                    request.send(null);
                    var returnValue = request.responseText;
                    return returnValue;
                }
            }
            var pathOfFileToRead = "file://d:/sampleData.txt";
            var contentsOfFileAsString = FileHelper.readStringFromFileAtPath
            (
                pathOfFileToRead
            );
            var contents_value = contentsOfFileAsString;
            alert(contents_value);
            document.getElementById("box").value = contents_value;
            //document.getElementById("demo").innerHTML = contents_value;       
            //get the contents of the text file STOP
</script>
</body>
</html>

在 JS 'pathOfFileToRead=filepath' 中,如果我将文件保存在同一个 htdocs 目录中,它工作正常,但如果我像在上面的 JS 中给出的那样提供本地目录路径,则无法正常工作。

你正在使用在浏览器中运行的javascript。不能使用 file://协议读取文件,也不能使用驱动器号。

不过,您仍然可以做您想做的事情。您需要使用 url 引用您的文件并使用 http://调用它。(你知道区别吗?!URL 具有指向 Web 根目录的域名或 IP 地址,然后可能是端口号,然后是分隔 Web 根目录下每个文件夹的正斜杠。Windows 路径具有驱动器号,然后用反斜杠分隔每个文件夹。

您的脚本中有很多需要改进的地方。我将从删除第 2 行上的一对空大括号开始。然后,我认为没有人在同步模式下使用 xmlhttp。您确实应该使用异步回调,并在开展业务之前检查成功(200)。