如何使用 JavaScript 从服务器读取文本文件?

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

How to read a text file from server using JavaScript?

javascriptajaxfile-io

提问by Woody

On the server, there is a text file. Using JavaScript on the client, I want to be able to read this file and process it. The format of the file on the server cannot be changed.

在服务器上,有一个文本文件。在客户端使用 JavaScript,我希望能够读取该文件并对其进行处理。无法更改服务器上文件的格式。

How can I get the contents of the file into JavaScript variables, so I can do this processing? The size of the file can be up to 3.5 MB, but it could easily be processed in chunks of, say, 100 lines (1 line is 50-100 chars).

如何将文件的内容放入 JavaScript 变量中,以便进行此处理?文件的大小可以高达 3.5 MB,但可以很容易地以 100 行(1 行是 50-100 个字符)的块进行处理。

None of the contents of the file should be visible to the user; he will see the results of the processing of the data in the file.

文件的任何内容都不应该对用户可见;他会看到文件中数据的处理结果。

回答by Shadow Wizard is Ear For You

You can use hidden frame, load the file in there and parse its contents.

您可以使用隐藏框架,在其中加载文件并解析其内容。

HTML:

HTML:

<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>

JavaScript:

JavaScript:

<script type="text/javascript">
function LoadFile() {
    var oFrame = document.getElementById("frmFile");
    var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
    while (strRawContents.indexOf("\r") >= 0)
        strRawContents = strRawContents.replace("\r", "");
    var arrLines = strRawContents.split("\n");
    alert("File " + oFrame.src + " has " + arrLines.length + " lines");
    for (var i = 0; i < arrLines.length; i++) {
        var curLine = arrLines[i];
        alert("Line #" + (i + 1) + " is: '" + curLine + "'");
    }
}
</script>

Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-filesflag. credit.

注意:为了使其在 Chrome 浏览器中工作,您应该使用--allow-file-access-from-files标志启动它。信用

回答by Amjad Masad

Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax()function.

加载那个巨大的数据块并不是一个很好的计划,但如果你必须这样做,这里是你可以如何使用jQuery 的$.ajax()函数来完成的大纲。

<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){

  $.ajax({
    url:'text.txt',
    success: function (data){
      //parse your data here
      //you can split into lines using data.split('\n') 
      //an use regex functions to effectively parse it
    }
  });
}
</script>
</head><body>
  <button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>

回答by Rafid

You need to use Ajax, which is basically sending a request to the server, then getting a JSON object, which you convert to a JavaScript object.

您需要使用 Ajax,它基本上是向服务器发送请求,然后获取一个 JSON 对象,然后将其转换为 JavaScript 对象。

Check this:

检查这个:

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

If you are using jQuery library, it can be even easier:

如果您使用的是 jQuery 库,它会更容易:

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

Having said this, I highly recommend you don't download a file of 3.5MB into JS! It is not a good idea. Do the processing on your server, then return the data after processing. Then if you want to get a new data, send a new Ajax request, process the request on server, then return the new data.

话虽如此,我强烈建议您不要将 3.5MB 的文件下载到 JS 中!这不是一个好主意。在您的服务器上进行处理,然后在处理后返回数据。然后如果你想获取新数据,发送一个新的 Ajax 请求,在服务器上处理请求,然后返回新数据。

Hope that helps.

希望有帮助。

回答by Noah Gary

I used Rafid's suggestion of using AJAX.

我使用了 Rafid 的使用 AJAX 的建议。

This worked for me:

这对我有用:

var url = "http://www.example.com/file.json";

var jsonFile = new XMLHttpRequest();
    jsonFile.open("GET",url,true);
    jsonFile.send();

    jsonFile.onreadystatechange = function() {
        if (jsonFile.readyState== 4 && jsonFile.status == 200) {
            document.getElementById("id-of-element").innerHTML = jsonFile.responseText;
        }
     }

I basically(almost literally) copied this code from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2so credit to them for everything.

我基本上(几乎是字面意思)从http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2复制了这段代码,所以一切都归功于他们。

I dont have much knowledge of how this works but you don't have to know how your brakes work to use them ;)

我对它的工作原理知之甚少,但您不必知道您的制动器如何工作才能使用它们;)

Hope this helps!

希望这可以帮助!

回答by Don Kirkby

It looks like XMLHttpRequesthas been replaced by the Fetch API. Google published a good introductionthat includes this example doing what you want:

看起来XMLHttpRequest已经被Fetch API取代了。谷歌发布了一个很好的介绍,包括这个例子做你想做的事:

fetch('./api/some.json')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

However, you probably want to call response.text()instead of response.json().

但是,您可能想要调用response.text()而不是response.json().

回答by Rahil Ali

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status and if it is from web server it returns the status)

您需要检查状态 0(如使用 XMLHttpRequest 在本地加载文件时,您不会获得状态,如果它来自 Web 服务器,则返回状态)

function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
    if(rawFile.readyState === 4)
    {
        if(rawFile.status === 200 || rawFile.status == 0)
        {
            var allText = rawFile.responseText;
            alert(allText);
        }
    }
}
rawFile.send(null);

}

}

For device file readuing use this:

对于设备文件读取使用这个:

readTextFile("file:///C:/your/path/to/file.txt");

readTextFile("file:///C:/your/path/to/file.txt");

For file reading from server use:

从服务器读取文件使用:

readTextFile("http://test/file.txt");

readTextFile(" http://test/file.txt");

回答by Dwight Spencer

I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.

我真的认为你以错误的方式处理这件事。试图下载和解析 +3Mb 的文本文件是完全疯狂的。为什么不在服务器端解析文件,将结果通过 ORM 存储到数据库(您的选择,SQL 很好,但它也取决于内容键值数据在 CouchDB 之类的东西上效果更好)然后使用 ajax 解析数据在客户端。

Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.

另外,如果可能的话,更好的主意是完全跳过文本文件以获得更好的性能。