JavaScript中导入库的未定义函数

时间:2015-07-29 17:27:02

标签: javascript jquery function csv

我正在将CSV文件解析为数组并使用jquery.csv来执行繁琐的工作。我的脚本是:

<script>
$(document).ready(function() {

// The event listener for the file upload
document.getElementById('txtFileUpload').addEventListener('change', upload, false);

// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
  var isCompatible = false;
  if (window.File && window.FileReader && window.FileList && window.Blob) {
    isCompatible = true;
  }
  return isCompatible;
}

// Method that reads and processes the selected file
function upload(evt) {
  if (!browserSupportFileUpload()) {
    alert('The File APIs are not fully supported in this browser!');
  } else {
    var data = null;
    var file = evt.target.files[0];
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function(event) {
      var csvData = event.target.result;
      data = $.csv.toArrays(csvData);
      if (data && data.length > 0) {
        alert('Imported -' + data.length + '- rows successfully!');
      } else {
        alert('No data to import!');
      }
    };
    reader.onerror = function() {
      alert('Unable to read ' + file.fileName);
    };
  }
}
});

我的控制台读到有一个&#34;未捕获的TypeError:无法读取属性&#39; toArrays&#39;未定义&#34;。同样在head部分,我使用<script src="jquery.csv-0.71.js"></script>导入了库,JS文件驻留在同一个文件夹中。有没有想过为什么会出现这种错误?我是否错误地导入了库,是否需要初始化某些内容?谢谢!

1 个答案:

答案 0 :(得分:0)

确保在导入jQuery之后导入jquery.csv-0.71.js 并确保您的脚本在两者之后运行。

<script src="jquery.js"></script>
<script src="jquery-csv.js"></script>
<script>/* Your script */</script>