简体   繁体   English

从JavaScript中的文本文件读取数据

[英]Read data from text file in javascript

I'm trying to make a complex website, and I want to split it into multiple files, one of them is the content itself, and for that I want to make a function that changes a div content from the file. 我正在尝试建立一个复杂的网站,我想将其拆分为多个文件,其中之一就是内容本身,为此,我想创建一个函数来更改文件中的div内容。

The entire code : 整个代码:

<html>
    <body onLoad = "uploadData();">
        <div id = "text"> </div>
    </body>
    <script>
    function uploadData()
    {
        var file = new File("data");
        file.open("r");
        var data = "";
        while (!file.eof) {
            data += file.readln() + "\n";
        }
        file.close();
        alert(data);
        document.getElementById('text').innerHTML = data;
    }
    </script>
</html>

The code has an error at line 7. Please help me !!! 代码在第7行有错误。请帮助我!

You cannot read from a file this way in a modern browser for security reasons (the scripts are sandboxed ). 出于安全原因,您不能在现代浏览器中以这种方式读取文件(脚本已沙盒化 )。

Maybe you took those functions from a very old and non-standard Javascript reference like JavaScript Programmer's Reference (by Cliff Wootton, 2001) or Pure JavaScript (by Charlton Ting, Jason Gilliam, Allen R. Wyke, 1999). 也许您是从非常老的非标准Javascript参考(例如JavaScript Programmer's Reference (Cliff Wootton,2001年)或Pure JavaScript (Charlton Ting,Jason Gilliam,Allen R. Wyke,1999年)中获得这些功能的。 Those are very antique manuals and deal with obsolete browser versions (Internet Explorer 4...). 这些都是非常古老的手册,并且处理过时的浏览器版本(Internet Explorer 4 ...)。

You can also find those functions or a similar set in the APIs provided by JS engines like Adobe InDesign, NodeJS or ShellJS, which are not browser engines . 您还可以在不是浏览器引擎的JS引擎(如Adobe InDesign,NodeJS或ShellJS)提供的API中找到这些功能或类似集合。 Working with a JS engine doens't imply you'll find the same API as provided by another one. 使用JS引擎并不意味着您会找到与另一个引擎相同的API。 Typically, you won't do the same things with NodeJS and Firefox JS engine (OdinMonkey currently). 通常,使用NodeJS和Firefox JS引擎(当前为OdinMonkey)不会做相同的事情。

If you want to dynamically change the content of your page (ie its DOM structure) with an external resource (a file located in your server), use the Ajax techniques. 如果要使用外部资源(位于服务器中的文件)动态更改页面的内容(即DOM结构),请使用Ajax技术。

Finally, in this SO question , you'll find some ways to get the content of a local file, but they must have been selected manually by the user. 最后, 在这个SO问题中 ,您将找到一些获取本地文件内容的方法,但是它们必须由用户手动选择

If you are creating a complex website, you need a web server. 如果要创建复杂的网站,则需要Web服务器。 Let's assume your content does not need server side rendering and you have Apache installed, then a plain XHR function can help you fetching the content. 假设您的内容不需要服务器端渲染并且已经安装了Apache,那么简单的XHR函数可以帮助您获取内容。 If plain XHR is not helpful, jQuery perhaps can ease things. 如果普通的XHR没有帮助,jQuery也许可以简化事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM