gpt4 book ai didi

javascript - 使用 JavaScript 读取服务器端文件

转载 作者:技术小花猫 更新时间:2023-10-29 12:39:01 26 4
gpt4 key购买 nike

我的网络服务器上有一个 JS 脚本,我希望它能够读取文件。我的文件系统是这样的:

> Root
index.html
read.js
> files
file.txt

在此示例中,文件“file.txt”将包含简单的单词“Hello”

用JavaScript,我希望能够做一个函数,例如:

function read (path) {
//Stuff to read the file with specified path
var content = //whatever the content is
return content;
}

然后可以调用它:

var file = read("/files/file.txt")

然后当我这样做的时候

alert(file)

它会弹出/提醒您“Hello”,file.txt 的内容。

有什么办法可以做到这一点吗?

最佳答案

这是一个示例网页:

http://sealevel.info/test_file_read.html

这是javascript代码:

// Synchronously read a text file from the web server with Ajax
//
// The filePath is relative to the web page folder.
// Example: myStuff = loadFile("Chuuk_data.txt");
//
// You can also pass a full URL, like http://sealevel.info/Chuuk1_data.json, but there
// might be Access-Control-Allow-Origin issues. I found it works okay in Firefox, Edge,
// or Opera, and works in IE 11 if the server is configured properly, but in Chrome it only
// works if the domains exactly match (and note that "xyz.com" & "www.xyz.com" don't match).
// Otherwise Chrome reports an error:
//
// No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sealevel.info' is therefore not allowed access.
//
// That happens even when "Access-Control-Allow-Origin *" is configured in .htaccess,
// and even though I verified the headers returned (you can use a header-checker site like
// http://www.webconfs.com/http-header-check.php to check it). I think it's a Chrome bug.
function loadFile(filePath) {
var result = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", filePath, false);
xmlhttp.send();
if (xmlhttp.status==200) {
result = xmlhttp.responseText;
}
return result;
}

关于javascript - 使用 JavaScript 读取服务器端文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com