我正在尝试将jquery(v.1.11.3)ajax与jquery.validate 1.15结合使用,以上载包含输入类型文件的表单。您可以从js注释行中看到我尝试过的所有内容。对于每个变体,php脚本都会返回“无图像文件”。当然,如果我删除了jquery脚本,那么表单将随页面刷新一起提交。我真的很想消除页面刷新,以获得更好的UX,但是我没有运气让它工作。如果有人可以帮助我修复我的代码,我将不胜感激。请注意:我研究了许多jquery ajax .post的示例,但是这些示例对我没有帮助,因为这些代码结构无法与Jquery.Validate插件一起使用。我也在这里找到了这个答案:文件上传PHP AJAX但是正如您从我的代码注释中看到的那样,我对此感到厌烦,没有运气。我肯定错过了什么。
<!DOCTYPE html>
<html>
<body>
<form action="imguploadTest.php" method="post" enctype="multipart/form-data" id="addItemsForm" name="addItemsForm">
<label>Select image to upload:</label>
<input type="file" name="itemImg" id="itemImg" />
<label>Name</label>
<input type="text" name="itemName" class="form-control" placeholder="Item Name..." maxlength="25" value="Really Cool Hoodie" />
<input type="submit" value="Upload Form" name="submit">
<div>
<div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if (element.parent('.radio-inline').length || element.parent('.checkbox-inline') ) {
error.insertAfter(element.parent().parent());
} else {
error.insertAfter(element);
}
}
});
$('#addItemsForm').validate({ // initialize the plugin
debug: true,
submitHandler: function(){
//var formData = $('#addItemsForm').serialize();
//var data = new FormData($('#addItemsForm'));
//var form = $('form')[0];
//var formData = new FormData(form);
//console.log(addform);
var frmData = new FormData($(this)[0]);
$.ajax({
url: "imgUploadTest.php",
data: frmData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
.done( function(res, jqXHR, textStatus) {
console.log(res);
//$('#results').html('<h4>Thumb link: ' + res["thumb"] + '<h4>');
//$('#results').append('<h4>Small link: ' + res["small"] + '<h4>');
//$('#results').append('<h4>Name: ' + res["name"] + '<h4>');
})
.fail( function (res, jqXHR, textStatus, errorThrown){
alert("failed! " + jqXHR, textStatus);
});
return false;
} // submitHandler
}); // validate
}); // doc ready
</script>
</body>
</html>
<?php
include 'imguploader.class.php';
// FUNCTIONS
function imagehandler($item_attr_ID) {
$imgId = $item_attr_ID;
$img = new imgUploader($_FILES['itemImg']);
$time = time();
$thumb = $img->upload('mobileApp/uploads/', $imgId.'_thumb', 100,100); // change these numbers for display
$small = $img->upload('mobileApp/uploads/', $imgId.'_small', 400,400); // change these numbers for display
//$full = $img->upload_unscaled('mobileApp/uploads/', $time);
if($thumb && $small){ // && $full
return array($thumb, $small);
/* TO SHOW IMAGE
echo '<img src="'.$thumb.'" alt="aPicture" /> <img src="'.$small.'" alt="aPicture" /> <img src="'.$full.'"alt="aPicture" />';
*/
} else {
echo ( 'ERROR! '.$img->getError() ); // --> error code 011.1
}
} // end imagehandler()
// Processes
if (!empty( $_FILES["itemImg"]) ){
$item_attr_ID = "jPlayerandtheGirls_8_1456";
list($item_img_thumb, $item_img_small) = imagehandler($item_attr_ID);
if ($item_img_thumb && $item_img_small){
$r["thumb"] = $item_img_thumb;
$r["small"] = $item_img_small;
} else {
$r["thumb"] = "No Thumb";
$r["small"] = "No Small";
$r["name"] = "Didn't get to name";
echo json_encode($r);
}
} else {
$r = "No image file";
echo json_encode($r);
}
if (!empty( $_POST["itemName"] )){
$r["name"] = $_POST["itemName"];
json_encode($r);
}
?>
好的,虽然我对JS / Jquery相对陌生,但我对它所涉及的理论并不十分确定,尽管我不能完全确定自己的问题。.serialize()不起作用。我认为这是因为根据定义,文件是二进制文件,因此无法序列化-但不要引用我。因此,您必须使用FormData发送文件。我知道这一点,但无法提出与jquery验证1.15一起使用的正确语法。请参阅下面的答案。希望它可以帮助某人节省一些时间。
首先用我的代码更正菜鸟错误:添加 type: 'post'
第二:用于保存表单数据(包括输入type =“ file”)的变量是这个 var formData = new FormData($('#useYourFormElementIdHere')[0]);
所以最后是这样的:
$.ajax({
type: "POST",
url: "imgUploadTest.php",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
}).done({}).fail({}).always({})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句