使用 JavaScript 从 1.dat 文件读取数据

Read Data from 1.dat File using JavaScript

这是我要 JavaScript 提出的第一个问题,因为我想将“1.dat”文件中的数据读入相应的文本字段/框中。

“1.dat”文件的 is 结构

    3  
    "Caroline Martin","2007 E.L Road","Los Angeles CA 87457",43  
    "Brian Green", "210 AB Street","New York NY 10002",52  
    "Amy Baker","3213 Canta Mount", "Miami FL 33133",61  

3-marker 没有3个人的记录:Name, Address1, Address2, Age.

那么,JavaScript中的结构应该如何编码,以便在HTML的各个文本框中读取和显示各个数据。

    <input id="txtName" type='text'/>
    <input id="txtAdd1" type='text'/>
    <input id="txtAdd2" type='text'/>
    <input id="txtAge" type='text'/>

我构建了一个示例,如何从 dat 文件中读取和解析数据,并将其分配到文本字段中:

1.dat 文件结构

3  
"Caroline Martin","2007 E.L Road","Los Angeles CA 87457",43  
"Brian Green", "210 AB Street","New York NY 10002",52  
"Amy Baker","3213 Canta Mount", "Miami FL 33133",61

HTML

<form>
<input id="txtName1" type='text'/>
<input id="txtAdd11" type='text'/>
<input id="txtAdd21" type='text'/>
<input id="txtAge1" type='text'/>

<input id="txtName2" type='text'/>
<input id="txtAdd12" type='text'/>
<input id="txtAdd22" type='text'/>
<input id="txtAge2" type='text'/>

<input id="txtName3" type='text'/>
<input id="txtAdd13" type='text'/>
<input id="txtAdd23" type='text'/>
<input id="txtAge3" type='text'/>
</form>

Javascript

var client = new XMLHttpRequest();
client.open('GET', '1.dat');
client.onload = (function(){

var txt = client.responseText;

var arr = [];
var lines = txt.split('\n');

for(j=1; j < lines.length; j++)
{
  lines[j] = lines[j].replace(/["]/g,'');
  arr[j] = lines[j].split(",");
  document.getElementById('txtName'+j).value = arr[j][0];
  document.getElementById('txtAdd1'+j).value = arr[j][1];
  document.getElementById('txtAdd2'+j).value = arr[j][2];
  document.getElementById('txtAge'+j).value = arr[j][3];
}

})
client.send(null);

完整代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Template</title>


  </head>
  <body>

<form>
<input id="txtName1" type='text'/>
<input id="txtAdd11" type='text'/>
<input id="txtAdd21" type='text'/>
<input id="txtAge1" type='text'/>

<input id="txtName2" type='text'/>
<input id="txtAdd12" type='text'/>
<input id="txtAdd22" type='text'/>
<input id="txtAge2" type='text'/>

<input id="txtName3" type='text'/>
<input id="txtAdd13" type='text'/>
<input id="txtAdd23" type='text'/>
<input id="txtAge3" type='text'/>
</form>
<SCRIPT TYPE="text/javascript">


var client = new XMLHttpRequest();
client.open('GET', '1.dat');
client.onload = (function(){

var txt = client.responseText;

var arr = [];
var lines = txt.split('\n');

for(j=1; j < lines.length; j++)
{
  lines[j] = lines[j].replace(/"/g,'');
  console.log(lines);
  arr[j] = lines[j].split(",");
  document.getElementById('txtName'+j).value = arr[j][0];
  document.getElementById('txtAdd1'+j).value = arr[j][1];
  document.getElementById('txtAdd2'+j).value = arr[j][2];
  document.getElementById('txtAge'+j).value = arr[j][3];
}

})
client.send(null);




</SCRIPT>


  </body>
</html>

由于安全限制,您不能自动打开本地文件(无需用户交互)!你会得到 "Cross origin requests are only supported for protocol schemes: http, data, ..."

我们必须在页面上放置一个输入文件,并在用户 select 一个文件时做一些事情。

编辑: 代码已更新以显示文件数据,使用 Prev/Next 按钮逐条记录

编辑 2: 更新以跳过 empty/incorrect 行:

<!DOCTYPE html>
<html>
<head>
  <title>File read test</title>

</head>

<body>

<p><input type='file' accept='*.dat' onchange='openFile(event)'></p>

<input type='button' id="btnPrev" value="Prev <" onclick="goRecord(-1)" />

<input type='text' id="txtName" />
<input type='text' id="txtAdd1" />
<input type='text' id="txtAdd2" />
<input type='text' id="txtAge" />

<input type='button' id="btnNext" value="> Next" onclick="goRecord(+1)" />


<script type="text/javascript">
  var data = [], cur;
  var inputs = ["txtName", "txtAdd1", "txtAdd2", "txtAge"]; //id of inputs

  function openFile(event) {

    var input = event.target;

    var reader = new FileReader();

    reader.onload = function () {
      var text = reader.result;
      //if (text!=null && text.length>0)
      var lines = text.split(/\r?\n/g); //split by newline chars to get all lines as array
      var k = -1;
      for (var i = 1; i < lines.length; i++) { //skip first line as it is Nlines
        var r = lines[i].replace(/"/g, "").split(","); //remove quotation marks and split to cols
        if (r.length == inputs.length) { //this row has correct number of columns (4)
          k++;
          data[k] = [];
          for (var j = 0; j < r.length; j++) {
            data[k][j] = r[j];
          }
        }
      }
      cur = 0; dispRecord(cur); //go to first record
    };

    reader.readAsText(input.files[0]);
  }

  function dispRecord(r) {
    var n = data[r].length;
    for (var j = 0; j < n; j++) {
      document.getElementById(inputs[j]).value = data[r][j];
    }
  }

  function goRecord(step) {
    var k = cur + step;
    if (k < 0) k = 0; else if (k >= data.length) k = data.length - 1;
    cur = k;
    dispRecord(cur);
  }

</script>

</body>
</html>

我在下面尝试实现我想要实现的目标但失败了

<!DOCTYPE html>
<html>
<head>
 <title>File read test</title>
</head>
<body>

<script type="text/javascript">
 var cur = 3;
 var openFile = function (event) {
 var input = event.target;

 var reader = new FileReader();
 reader.onload = function () {
 var text = reader.result;
 var lines = text.split(/\r?\n/g);
 var n = parseInt(lines[0], 10); //10 is radix
 var s = "", i = 0;
 for (var c = 0; c < n; c++) {
  var row = lines[++i].replace(/"/g, "").split(","); //remove quotation marks and split to cols
 for (var t = 0; t < 4; t++) {
   s += "<input type='text' id='txtName' value=\"" +  row[t].replace(/^\s+|\s+$/g, "") + "\" /> \r\n";
  }
  s += "<br/>";
}
//if (text!=null && text.length>0)
document.getElementById('myConainer').innerHTML = s;
};
reader.readAsText(input.files[0]);
};

function dispValue() {   
   document.getElementById('txtName').value = Names[i];   
   document.getElementById('txtAdd1').value = Add1[i];   
   document.getElementById('txtAdd2').value = Add2[i];   
   document.getElementById('txtAge').value = Age[i]; 
 }
function cmdNext() {    
if(i<cur-1) {      
   i = i + 1;      
  dispValue();    
 }
 }

function cmdPrevious() {   
 if(i>0) {      
  i = i - 1; 
 dispValue(); 
} 
}      

</script>
<input type='file' accept='*.dat' onchange='openFile(event)'> <br/>
<div id="myConainer">
</div>
</body>
</html>

具体需要做什么?因为当按下一个命令时应该显示另一条记录并且按下上一个按钮应该显示上一个记录即为什么只有四个文本框来分别读取所有 3 个记录。所以基本上每个 Name Add1 Add2 和 Age 都可以从 1.dat 文件

中读取相应的 4 个文本框