使用JavaScript读取服务器端文件 [英] Read A Server Side File Using JavaScript

查看:158
本文介绍了使用JavaScript读取服务器端文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

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")

然后当我这样做

alert(file)

它将弹出并提示您".Hello",即file.txt的内容.

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

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

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

推荐答案

以下是为您提供的示例网页:

Here's a sample web page for you:

http://sealevel.info/test_file_read.html

这是JavaScript代码:

Here's the javascript code:

// 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读取服务器端文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆