javascript - 无法在 PHP AJAX 请求中发送文件

标签 javascript php jquery ajax

我无法在 PHP AJAX 请求中发送文件:

表格:

<form class="frmContact" action="#" method="post">
                  <div class="col-md-6">  
                     <input type="hidden" name="emailTo" id="emailTo" value="example@domain.com">     
                     <input type="text" placeholder="Name" name="txtName" id="txtName">
                     <input type="email" placeholder="Email" name="txtEmail" id="txtEmail">
                     <input type="text" placeholder="Subject" name="txtSubject" id="txtSubject">

                     <input type="file" placeholder="Text File" name="txtFile" id="txtFile" />

                  </div>
                  <div class="col-md-6">  
                     <textarea placeholder="Message" cols="40" rows="10" name="txtText" id="txtText"></textarea>
                     <button class="btnSend" type="button">Send Your Message</button>
                     <span id="spanMessage"></span>
                  </div>
               </form>

Ajax 代码:

$.ajax({
        url: "includes/mail.php", // Url to which the request is send
        type: "POST",             // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data)   // A function to be called if request succeeds
        {
        console.log(data);
        }
        });

PHP 代码:

echo '<pre>'; print_r($_REQUEST); print_r($_FILES);  die;

控制台结果:

Array
(
)

Array
(
)

使用 jQuery jQuery v1.11.2

你能帮我调试这个错误吗?

最佳答案

您忘记了enctype="multipart/form-data"。请将其添加到表单标记中:

<form class="frmContact" action="#" method="post" enctype="multipart/form-data">

关于javascript - 无法在 PHP AJAX 请求中发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32222234/

相关文章:

javascript - 使用嵌套映射的 JSON 对象反序列化,Java Spring

php - 无法通过 PHP 将 NSData 上传到 MySQL

javascript - 用 jQuery 高亮一个词

javascript - Wordpress - 更新数据库后如何刷新页面

javascript - 蒙戈日期问题

javascript - 如何在 dijit.form.Form 上突出显示所有无效的 dijit.form.ValidationTextBoxes?

php - 类 Entities\USER_User 中的注释 "@Doctrine\ORM\Mapping\Entity"不存在,或者无法自动加载

php - Doctrine 自动递增起始值 @ORM\GeneratedValue

javascript - 无法选择 JQuery(移动)/JavaScript 选择选项

javascript - 如何设置 href 以 Bootstrap 导航栏 onclick 菜单它应该触发到另一个页面的标签栏