用javascript读取服务器文件 [英] reading server file with javascript

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

问题描述

我有一个使用javascript的html页面,用户可以选择从他的PC上阅读和使用自己的文本文件。但我希望在服务器上有一个示例文件,用户可以通过单击按钮打开该文件。
我不知道打开服务器文件的最佳方法是什么。我用谷歌搜索了一下。 (我是html和javascript的新手,所以也许我对以下内容的理解不正确!)。我发现javascript是基于客户端的,打开服务器文件并不是很简单。看起来最简单的方法是使用iframe(?)。
所以我正在尝试(第一次测试只是为了打开网页的onload)以下内容。将kgr.bss放在服务器上与我的html页面相同的目录中:

I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button. I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?). So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:

<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>

和(使用file_inhoud,其他地方定义的行)

and (with file_inhoud, lines defined elsewhere)

function readFile() {
    func="readFile=";
    debug2("0");
    var x=document.getElementById("myframe");
    debug2("1");
    var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
    debug2("1a"+doc);
    var file_inhoud=doc.document.body;
    debug2("2:");
    lines = file_inhoud.split("\n");
    debug2("3");
    fileloaded();
    debug2("4");
}

调试功能显示:

readFile=0//readFile=1//readFile=1a[object HTMLDocument]//

所以停止程序的语句是:

So statement that stops the program is:

var file_inhoud=doc.document.body;

有什么问题?读取此文件的正确(或最佳)方式是什么?

What is wrong? What is correct (or best) way to read this file?

注意:我看到文件被读取并显示在框架中。

Note: I see that the file is read and displayed in the frame.

谢谢!

推荐答案

检索文本文件(或任何其他服务器端资源)的常用方法)是使用 AJAX 。以下是如何提醒文本文件内容的示例:

The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:

var xhr;
if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();

然而,您最终目标的问题在于,传统上无法使用javascript访问客户端文件系统。但是,新的HTML5文件API正在改变这一点。您可以在此处上阅读。

The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.

这篇关于用javascript读取服务器文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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