我想使用jquery,ajax和php使用多个接受输入来验证和上传图像。我添加了正常工作的验证功能,但表单没有提交,chrome和firefox在控制台中显示不同的错误。
<form id="promotionImageForm_<?php echo $row['pm_id']; ?>" autocomplete="off" enctype="multipart/form-data">
<label>Add More Images</label>
<input type="file" name="pm_image[]" class="form-control" multiple="multiple" id="pmMultiImgs_<?php echo $row['pm_id']; ?>" />
<input type="hidden" name="pm_id" value="<?php echo $row['pm_id']; ?>" />
<input type="hidden" name="uploadImageByID" value="uploadImageByID" />
<button type="button" onclick="return multiImageUpload(<?php echo $row['pm_id']; ?>);" id="pmMultibTn" />Add</button>
</form>
function uploadImageByID(formData){
$.ajax({
type:'POST',
url:'response.php',
data:formData,
dataType:"json",
success: function(response){
$(".pmImgPopNoti").remove();
if(response.success){
$(".pmRes_"+promotionImageID).prepend('<div id="login-alert" class="alert alert-success pmImgPopNoti col-sm-12">'+response.success+'</div>');
}
if(response.error){
$(".pmRes_"+promotionImageID).prepend('<div id="login-alert" class="alert alert-danger pmImgPopNoti col-sm-12">'+response.error+'</div>');
}
}
});
}
function multiImageUpload(pmID){
$('#promotionImageForm_'+pmID).validate();
$('#pmMultiImgs_'+pmID).each(function() {
$(this).rules("add", {
required: true,
accept: "image/jpeg, image/pjpeg, image/png",
messages: {
accept: "Only jpeg, jpg or png images"
}
});
});
if ($('#promotionImageForm_'+pmID).valid()) {
var formDetail = $('#promotionImageForm_'+pmID);
var formData = new FormData(formDetail);
uploadImageByID(formData);
return false;
}
}
Chrome显示此错误
未捕获的TypeError:非法调用
FireFox显示此错误
TypeError:FormData.constructor的参数1未实现接口HTMLFormElement。 var formData = new FormData(formDetail);
任何人都可以指导我如何解决此错误。如果有人指导我,我很感激。谢谢
答案 0 :(得分:2)
FormData
对象构造函数需要form
元素,而不是包含表单的jQuery对象。试试这个:
if ($('#promotionImageForm_'+pmID).valid()) {
var formDetail = $('#promotionImageForm_' + pmID);
var formData = new FormData(formDetail[0]); // note [0] here
uploadImageByID(formData);
return false;
}