使用 JavaScript 读取服务器端文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36921947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:43:34  来源:igfitidea点击:

Read A Server Side File Using JavaScript

javascripthtml

提问by Gabriel Dunn

I have on my web server a JS script that I want to be able to read files. My filesystem is like this:

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

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

In this example, the file "file.txt" will contain the simple word "Hello"

在这个例子中,文件“file.txt”将包含简单的单词“Hello”

With JavaScript, I wish to be able to make a function, for example:

使用 JavaScript,我希望能够创建一个函数,例如:

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

And then be able to call it with:

然后可以调用它:

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

And then when I do

然后当我做

alert(file)

It will pop up with/alert you with "Hello", the content of file.txt.

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

Is there any way that I would be able to do this?

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

回答by Dave Burton

Here's a sample web page for you:

这是一个示例网页:

http://sealevel.info/test_file_read.html

http://sealevel.info/test_file_read.html

Here's the javascript code:

这是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;
}

回答by Matthias Winkelmann

What you're looking for is XMLHttpRequest.

您正在寻找的是XMLHttpRequest

回答by AutomationNation

This is a very simple task if you are using JQuery - The below example will perform an HTTP GET request (using XMLHttpRequest.as referenced above) and will put the contents into an HTML DOM object with the ID of "result". It will also throw an alert box up once the load is completed.

如果您使用 JQuery,这是一项非常简单的任务 - 下面的示例将执行 HTTP GET 请求(使用上面引用的 XMLHttpRequest.)并将内容放入 ID 为“result”的 HTML DOM 对象中。一旦加载完成,它也会抛出一个警告框。

$( "#result" ).load( "files/file.txt", function() {
  alert( "Load was performed." );
});

回答by Dan Schalow

You want to be using XMLHttpRequest, like Gabriel has suggested.

您想使用XMLHttpRequest,就像加布里埃尔建议的那样。

You seriously need to read up on it, since it is very configurable and you need to understand the workflow in order to implement it. You will run into problems initially, if you are cross origin scripting.

你真的需要仔细阅读它,因为它是非常可配置的,你需要了解工作流程才能实现它。如果您是跨源脚本编写,您最初会遇到问题。

Here is an example I mocked up for you:

这是我为你模拟的一个例子:

<span id="placeholder"></span>
<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById('placeholder').innerHTML = xhr.responseText;
        }
    }
    xhr.open('GET', 'test.html');
    xhr.send();
</script>

回答by SamuelN

It's not as simple as it sounds and you are going to have to do some research on server vs client.

这并不像听起来那么简单,您将不得不对服务器与客户端进行一些研究。

You cannot read server side data through Javascript unless you have a connection to the server. Whatever Javascript code that runs on the client's browser will remain on their browser only, even if both are ran on the same computer. What you need is a way to make the client (in this case, the html+javascript website) communicate with the server.

除非连接到服务器,否则无法通过 Javascript 读取服务器端数据。在客户端浏览器上运行的任何 Javascript 代码都将只保留在他们的浏览器上,即使两者都在同一台计算机上运行。您需要的是一种使客户端(在本例中为 html+javascript 网站)与服务器通信的方法。

There are endless ways to do this but the most simple is through a GET request to a server that is serving that text file.

有无数种方法可以做到这一点,但最简单的是通过对提供该文本文件的服务器的 GET 请求。

Try looking into serving static files with NGINX or maybe something like NodeJS, depending on what meets your needs. From there, create a GET endpoint that your Javascript is going to connect to through an XMLHttpRequest (like @MattW. said).

尝试研究使用 NGINX 或 NodeJS 之类的东西来提供静态文件,这取决于满足您的需求。从那里,创建一个 GET 端点,您的 Javascript 将通过 XMLHttpRequest 连接到该端点(如@MattW. 所说)。