使用Ajax将FormData对象发送到服务器(包含文件)

时间:2015-07-16 16:12:24

标签: php jquery ajax multipartform-data

我有一个包含文本和文件字段的表单。我试图将整个事情提交给托管在服务器上的php脚本,并返回验证消息。我的表格如下:

    <form id="ambassador" method="post" enctype="multipart/form-data">
        <label for="name">Name: </label>
        <input type="text" id="name"> <br />
        <label for="age">Age: </label>
        <input type="number" id="age"> <br />
        <label for="igram">Instagram Account: </label>
        <input type="text" id="igram"> <br />
        <label for="photo">Photograph Upload: </label>
        <input type="file" id="photo"><br />
        <label for="why">Why should you represent Drip Cold Pressed Juice?</label>
        <textarea id="why" width="300px"></textarea>
        <button type="submit" class="btn">Apply!</button>
    </form>

我的jQuery看起来像:

jQuery("#ambassador").submit(function(event) {
    event.preventDefault
    var server = "http://getdripped.com/dev/ambassador.php";

    var form = document.getElementById('#ambassador');
    var formData = new FormData(form);

    alert(formData);


    jQuery.ajax({
        url: server,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;  
});

php只包含print_r数组的$_FILES语句和$_POST数组的另一个语句。但是两个返回的数组都是空的。

3 个答案:

答案 0 :(得分:1)

你有两个问题。

未能将表单传递给FormData对象

document.getElementById('#ambassador');

getElementById方法采用 ID ,但您传递选择。您需要删除#。目前您正在将null传递给new FormData(因为没有匹配的元素,因此gEBId会返回null)。

表格

中没有成功的数据
<input type="number" id="age">

表单控件只有在具有name属性且没有属性的情况下才能成功。

更正ID后,您将使用表单中的所有成功控件填充表单数据对象:但是没有。

您需要为每个输入添加名称属性。

答案 1 :(得分:0)

我会使用iframe作为表单的目标。

   <form id="ambassador" method="post" enctype="multipart/form-data" target="form_iframe" >

    <iframe name="form_iframe" id="form_iframe" ></iframe>

另见How to make Asynchronous(AJAX) File Upload using iframe?

答案 2 :(得分:0)

忽略downvote,

将async设置为true!

您将async设置为false。这意味着您的成功回调将不会等待回复并在PHP回答之前很久就完成。

如果您遇到更多麻烦,请查看this SO Question因为已经有答案。

来自jQuery Documentation

  

请注意,同步请求可能会暂时锁定浏览器,并在请求处于活动状态时禁用任何操作。

Quentin对序列化是正确的,我在进一步阅读后删除了序列化选项。

相关问题