我已经通过Ajax提交了表单,我无法在此提交中上传图片
<form id="forms-items" name="forms-items" method="post" enctype="multipart/form-data"> <input id="uploadBtn" name="uploadimg" type="file" class="upload" /> </form
在提交代码中
if($_FILES['uploadimg']['size']>0) { $ftype=$_FILES["uploadimg"]["type"]; if(move_uploaded_file($_FILES['uploadimg']['tmp_name'], $target_path)) { $default=1; $mesg="File Uploaded Successfully"; } else $mesg="File Uploading Failed!!"; else $mesg="Please Select A File";
输出: Please Select A File
Please Select A File
JavaScript代码
$("#forms-items").submit(function() { $.ajax({ url: "ajax/submitform.php", type: "POST", data: $("#forms-items").serialize(), success: function(response) { alert(response); } }); });
使用FormData()该类最简单:
FormData()
因此,现在您有了一个FormData对象,准备与XMLHttpRequest一起发送。并使用FormData对象附加字段
<script type="text/javascript"> $(document).ready(function () { var form = $('#forms-items'); //valid form selector form.on('submit', function (c) { c.preventDefault(); var data = new FormData(); $.each($(':input', form ), function(i, fileds){ data.append($(fileds).attr('name'), $(fileds).val()); }); $.each($('input[type=file]',form )[0].files, function (i, file) { data.append(file.name, file); }); $.ajax({ url: 'ajax/submitform.php', data: data, cache: false, contentType: false, processData: false, type: 'POST', success: function (c) { //code here if you want to show any success message alert(response); } }); return false; }); }) </script>
并强制jQuery不要为您添加Content-Type标头,否则,上传文件边界字符串将丢失。