Php 使用ajax提交时文件上载失败,返回false

Php 使用ajax提交时文件上载失败,返回false,php,jquery,ajax,Php,Jquery,Ajax,我有一个表单,它有一个简单的文件输入 <form id="uploadFile" name="uploadFile" action="addFile.php" method="POST" enctype="multipart/form-data"> <input type="hidden" value="" name="uploadWUID" id="uploadWUID"> <p>Please upload a signed and comp

我有一个表单,它有一个简单的文件输入

<form id="uploadFile" name="uploadFile" action="addFile.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" value="" name="uploadWUID" id="uploadWUID">
    <p>Please upload a signed and completed write-up in PDF format.  Please file the hardcopy of the write-up per company policy.</p>
    <div class="input-group" style="margin-bottom:7px;">
        <span class="input-group-btn">
            <span class="btn btn-primary btn-file">
                Browse&hellip; <input type="file" id="reportImport" name="reportImport">
            </span>
        </span>
        <input type="text" class="form-control" readonly>
    </div>
</form>

更改脚本代码

$('#uploadFile').submit(function() {
        var formData = new FormData($(this)[0]);              
        $.ajax({
          data: formData,
          type: $(this).attr('method'),
          url: $(this).attr('action'),
          processData: false,  // tell jQuery not to process the data
          contentType: false,  // tell jQuery not to set contentType
          success: function(response) {
             console.log(response);
             alert(response);
             return false
          }
        });
     return false;
 });

请注意,javascript是同步执行的-尝试在成功处理程序中返回
false
值:
success:function(response){return false}
是否需要返回false@messerbill,这允许表单正确提交,但不会阻止页面指向addFile.php页面。我需要返回false以避免重定向浏览器。想要停留在我的当前页面上。所以不要使用
submit
,而是在单击按钮后使用一个简单的ajax调用。由于您使用的是
ajax
;),因此无需提交表单即可向服务器发送数据这成功了!非常感谢你。我现在的问题是为什么?调用中缺少的是processData和contentType吗?@Pieter必须将contentType选项设置为false,强制jQuery不要为您添加内容类型头,否则,它将缺少边界字符串。另外,您必须将processData标志设置为false,否则,jQuery将尝试将FormData转换为字符串,这将失败。感谢您的解释,这是有意义的。我一辈子都不明白为什么它会像我不想停留在当前页面上一样完整。
$('#uploadFile').submit(function() {
        var formData = new FormData($(this)[0]);              
        $.ajax({
          data: formData,
          type: $(this).attr('method'),
          url: $(this).attr('action'),
          processData: false,  // tell jQuery not to process the data
          contentType: false,  // tell jQuery not to set contentType
          success: function(response) {
             console.log(response);
             alert(response);
             return false
          }
        });
     return false;
 });