使用 jquery 从 javascript 加载 .txt 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3304433/
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-10-25 00:47:36  来源:igfitidea点击:

Load .txt file from javascript with jquery

javascriptjqueryloadtext-files

提问by Luccas

I want to load a local .txt file and work with the content in javascript. My local file is like C:\Users\Who\Desktop\file.txt Thanks

我想加载一个本地 .txt 文件并使用 javascript 中的内容。我的本地文件就像 C:\Users\Who\Desktop\file.txt 谢谢

采纳答案by Elf King

by default javascript is NOT allowed to access local file system for security reasons. If you want to allow a particular script access to a local file then you have 2 options.

默认情况下,出于安全原因,不允许 javascript 访问本地文件系统。如果要允许特定脚本访问本地文件,则有 2 个选项。

1a. Change your model, put the text file on a server and load from there...

1a. 更改您的模型,将文本文件放在服务器上并从那里加载...

1b. Run a local webserver :-)

1b. 运行本地网络服务器:-)

2 ... this becomes browser dependent,

2 ...这变得依赖于浏览器,

In particular,

特别是,

回答by Anders

You can't, place it on a web server (on the same domain you are working on) then perform an AJAX GET.

你不能,把它放在一个网络服务器上(在你工作的同一个域上)然后执行 AJAX GET。

var file = (function func1() {
    var result;

    $.ajax({
        type: "GET",
        url: file,
        async: false,
        success: function(data){
            result = data;
        }
    });
    return result;
})();

回答by Henrik Joreteg

I'm guessing by your question that maybe you're trying to do some form of JS templating. In which case, you'd probably want to look at something like this: http://github.com/andyet/icanhaz.js

我猜你的问题,也许你正在尝试做某种形式的 JS 模板。在这种情况下,您可能想查看以下内容:http: //github.com/andyet/icanhaz.js

The short of it is, you can store text that you want access to in JS in this way:

简而言之,您可以通过这种方式在 JS 中存储您想要访问的文本:

<script id="my_snippet" type="text/html">
    Whatever random text here, format doesn't really matter,
    you can use whatever unless  you're trying to serve it as xml.
</script>

It's actually valid in HTML 5. Then you can retrieve the contents in JS like so:

它实际上在 HTML 5 中有效。然后您可以像这样在 JS 中检索内容:

$('#my_snippet').html();

$('#my_snippet').html();

ICanHaz.js abstracts this all a bit for you so if you're templating... I'd recommend using that instead.

ICanHaz.js 为你抽象了这一切,所以如果你正在做模板......我建议改用它。

回答by Bryon Hibbetts

Allowing a website to access c:\path\file.xxx on the client's computer is a major security breach. Javascript will never have this functionality.

允许网站访问客户端计算机上的 c:\path\file.xxx 是一个重大的安全漏洞。Javascript 永远不会有这个功能。

回答by μBio

You could instantiate a WebBrowser control, use C# to load the .txt file contents into a div or something and go from there.

您可以实例化 WebBrowser 控件,使用 C# 将 .txt 文件内容加载到 div 或其他内容中,然后从那里开始。