在javascript

时间:2016-03-08 02:25:42

标签: javascript csv

在下面的代码中,我能够从逗号分隔的textarea中读取并将数据存储到数组中。 textarea的ID为' input2'并且所有值都从input2传递到变量'输入'在功能中。

如何通过阅读csv文件而不是textarea来实现相同的目标?

<html>
<head>

</head>

<body>
<h1>CSV parser</h1>
<p>We will attempt to parse a CSV file</p>

<button type="button" onclick="example2()">Load the CSV file</button> 

<br><br>

 <textarea id="input2" style="height:150px;">"All work","and no play","makes     Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."
"All work","and no play","makes Jack","a dull boy..."</textarea>

<br><br>

<table id="result2" border="1"></table>

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script></script>
<script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js">        </script>

<script>

    function example2() {
      var input = $('#input2').val();
      var data = $.csv.toArrays(input);
      var html = generateTable(data);
      $('#result2').empty();
      $('#result2').html(html);
    }

    function generateTable(data) {
      var html = '';

      if(typeof(data[0]) === 'undefined') {
        return null;
      }

      if(data[0].constructor === Array) {
        for(var row in data) {
          html += '<tr>\r\n';
          for(var item in data[row]) {
            html += '<td>' + data[row][item] + '</td>\r\n';
          }
          html += '</tr>\r\n';
        }
      }

  return html;
}

</script>

</body>

</html>

0 个答案:

没有答案