2016-12-16 121 views
0

如何將var validEmails返回到checkform()。現在是undefinedFileReader()返回值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> 

回答

0

validEmails變量位於onload函數的範圍內。要麼定義它的功能或刪除「var」(這將使其成爲全局變量)。

您應該檢查javascript的變量範圍http://www.w3schools.com/js/js_scope.asp

+0

如何避免全局變量?爲什麼不可能簡單地返回值?範圍並不意味着它不能被退回。 – Zelphir