Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

jQuery: read text file from file system

I am trying to read a text file using jquery, like this:

// LOAD file and split line by line and append divs
$.get('myFile.txt', function(data) {    
    var lines = data.split("
");

    $.each(lines, function(n, elem) {
       $('#myContainer').append('<div>' + elem + '</div>');
    });
});

In chrome, I am getting:

XMLHttpRequest cannot load file:///C:/myPath/myFile.txt. Origin null is not allowed by Access-Control-Allow-Origin.

Firefox shows no error but the code is not executed (I have breakpoints in firebug and the anonymous function never runs).

Any help appreciated!

EDIT:

had to:

  • use the file full path
  • launch chrome with "--allow-file-access-from-files"

now it's working OK!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't load a file from your local filesystem, like this, you need to put it on a a web server and load it from there. On the same site as you have the JavaScript loaded from.

EDIT: Looking at this thread, you can start chrome using option --allow-file-access-from-files, which would allow access to local files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...