简体   繁体   English

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

[英]How to read a text file from server using JavaScript?

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.在客户端使用 JavaScript,我希望能够读取该文件并对其进行处理。 The format of the file on the server cannot be changed.无法更改服务器上文件的格式。

How can I get the contents of the file into JavaScript variables, so I can do this processing?如何将文件内容放入 JavaScript 变量中,以便进行此处理? 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).文件的大小可以高达 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.他会看到文件中数据的处理结果。

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-files flag.注意:为了使其在 Chrome 浏览器中工作,您应该使用--allow-file-access-from-files标志启动它。 credit . 信用

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>

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!话虽如此,我强烈建议您不要将 3.5MB 的文件下载到 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.然后如果你想得到一个新的数据,发送一个新的 Ajax 请求,在服务器上处理这个请求,然后返回新的数据。

Hope that helps.希望有帮助。

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_get2 so 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!希望这有帮助!

It looks like XMLHttpRequest has been replaced by the Fetch API .看起来XMLHttpRequest已被Fetch API取代。 Google published a good introduction that includes this example doing what you want:谷歌发布了一个很好的介绍,包括这个例子做你想做的事:

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()

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");

For file reading from server use:从服务器读取文件使用:

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

Just a small point, I see some of the answers using innerhtml.只是一点点,我看到一些使用innerhtml的答案。 I have toyed with a similar idea but decided not too, In the latest version react version the same process is now called dangerouslyinnerhtml, as you are giving your client a way into your OS by presenting html in the app.我曾考虑过类似的想法,但我决定不这样做,在最新版本的反应版本中,相同的过程现在称为危险的内部 HTML,因为您通过在应用程序中呈现 html 来让您的客户进入您的操作系统。 This could lead to various attacks as well as SQL injection attempts这可能导致各种攻击以及 SQL 注入尝试

I really think your going about this in the wrong manner.我真的认为你以错误的方式处理这件事。 Trying to download and parse a +3Mb text file is complete insanity.试图下载和解析 +3Mb 的文本文件是完全疯狂的。 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.为什么不在服务器端解析文件,将结果通过 ORM 存储到数据库(您的选择,SQL 很好,但它也取决于内容键值数据在 CouchDB 之类的东西上效果更好)然后使用 ajax 解析数据在客户端。

Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.另外,如果可能的话,更好的主意是完全跳过文本文件以获得更好的性能。

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

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