我想知道是否可以在表单的enctype上设置"切换系统",我解释道:我有一个不需要$_Files的表单。。若我有一个上传文件,一切都正常,但若我没有,我会收到一封空邮件,但邮件头很好。我认为这是因为enctype,我不知道如何对进行操作。
对于我们日常的许多UI问题,jQuery可以是一个方便的解决方案。。。我准备了这个简单的html表单:
<form id="myform" method="POST" action="myActionFile.php">
<div>First Name <span>*</span><input class="form-control" type="text" id="firstname" name="firstname"></div>
<div>Last Name <span>*</span><input class="form-control" type="text" id="lastname" name="lastname"></div>
<div>Your File: <input class="form-control" type="file" id="myfile" name="myfile"></div>
<div><button class="btn pull-right" id="submit">SEND</button></div>
</form>
正如您在"form"标记中看到的,"enctype"不包括在内。这将由javascript(实际上是jQuery)负责:
$('#submit').on('click', function(e){
e.preventDefault();
if($('#firstname').val().length < 1){$('#firstname').css('background-color', '#ffc9c9').prop('placeholder', 'Required');}
if($('#lastname').val().length < 1){$('#lastname').css('background-color', '#ffc9c9').prop('placeholder', 'Required');}else{
var fileData = $('#myfile').val();
if(fileData != ""){ //if file has been selected:
$('#myform').prop('enctype', 'multipart/form-data').submit();
}else{ //if NO file selected:
$('#myform').prop('enctype', 'text/plain').submit();
}
}
});
上述代码
检查所需字段(名字、姓氏)是否为空
检查"文件"输入(无论是否为空),并为表单指定正确的"enctype"
最后,提交表单
这是小提琴:http://jsfiddle.net/8y2y5z4s/