Load .txt file from javascript with jquery [closed]

孤街醉人 提交于 2019-12-23 11:56:15

问题


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


回答1:


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.

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

1b. Run a local webserver :-)

2 ... this becomes browser dependent,

In particular,

  • you can create a signed javascript for Mozilla like browsers, see http://www.mozilla.org/projects/security/components/signed-scripts.html for details

  • you can create an ActiveX plugin that allows local access for IE types... ;

  • and for anything else again read up o local access.




回答2:


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

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

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



回答3:


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

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

<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:

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

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




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/3304433/load-txt-file-from-javascript-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!