FileReader()返回值undefined

时间:2016-12-16 00:17:43

标签: javascript filereader fileapi

如何将var validEmails返回checkform()。它现在是undefined

<script type="text/javascript">
function checkfile(form) {

  var reader = new FileReader();

  reader.onload = function(e) {
    var emails = e.target.result;
    var validEmails = parseEmails(emails);
    return validEmails;
  };

  var formFiles = form.files[0];
  reader.readAsText(formFiles);

  function parseEmails(emails) {
    var obj = Papa.parse(emails, { skipEmptyLines: true });

    var valid = 1;
    $.each(obj.data, function(i, v) {
      var email = v[0].trim();
      valid = validEmail(email);
    });

    return valid;
  };

  function validEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
  };
}

function checkform(form) {
  console.log( checkfile( document.getElementById('recipient_csv') ) );
}
</script>

<form method="post" action="/" enctype="multipart/form-data" onSubmit="return checkform(this);">

  <input id="recipient_csv" type="file" name="recipient_csv" />

</form>

1 个答案:

答案 0 :(得分:0)

validEmails变量在onload函数的范围内。要么将其定义为函数,要么删除“var”(这将使其成为全局变量)。

您应该检查javascript http://www.w3schools.com/js/js_scope.asp

的变量范围