这是我的代码:
<form enctype="multipart/form-data" id="myform">
<div class="input">
<textarea name="comments" id="comments"></textarea>
</div>
<div class="attachment">
<input type="file" name="attachement" id="attachement"/>
</div>
<input type="button" value="Send" id="btn_send" />
</form>
我的脚本是:
<script>
function showFileSize() {
var input, file;
if (!window.FileReader) {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('attachement');
file = input.files[0];
var expi= file.name.toLowerCase().split(".");
if((expi[1]=='jpg')||(expi[1]=='jpeg')||(expi[1]=='png')||(expi[1]=='gif'))
{
return true;
}
else {
alert("Invalid file format");
return false;
}
}
和ajax将文件发布到action.php
$('#btn_send').live('click', function() {
var comments = $('textarea#comments').val();
var imgVal = $('#attachement').val();
if(comments=='')
{
alert("Enter comments");
$('textarea#comments').focus();
return false;
}
if(imgVal!='')
{
return showFileSize();
}
var formData = new FormData($('#myform')[0]);
$.ajax({
type: "POST",
url: "action.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function() {
}
});
});
每当我选择不是图像文件时,它都会显示警告&#34;无效的文件格式&#34;,但是当我选择正确的文件类型时,它不会发布值? 怎么修理? 感谢
答案 0 :(得分:1)
错误在于:
if(imgVal!='')
{
return showFileSize();
}
当click事件处理程序到达此点时,返回会在您到达ajax请求之前阻止该函数。
我想你想要的东西是这样的:
$('#btn_send').live('click', function() {
var comments = $('textarea#comments').val();
var imgVal = $('#attachement').val();
if(comments=='')
{
alert("Enter comments");
$('textarea#comments').focus();
return false;
}
if(imgVal!='')
{
if (showFileSize())
{
var formData = new FormData($('#myform')[0]);
$.ajax({
type: "POST",
url: "action.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function() {
}
});
}
}
});
否则你总是返回