jquery ajax post 文件,多个文件和文本输入

jquery ajax post file , multiple files and text input

大家好,我的 html 代码:

<form action="post.php" enctype="multipart/form-data" method="post">
   <input type="text" name="name" id=""><br>
   <input type="file" name="poster" id="poster"><br>
   <input type="file" name="scene[]" id="scene" multiple><br>
   <input type="submit" value="POST">
</form>

如您所见,单个文件、多个文件,而我有一个文本值。此值 'ajax' 与要发送一次。 'JQuery'我用。

我无论如何都不能运行

$(function(){
        $('input[type="submit"]').click(function(e){
            e.preventDefault();
            var file_data = $('#poster').prop('files')[0];
            var form = $('form').serialize();
            var form_data = new FormData();
            $.each($('input[name="scene[]"]'),function(i, obj) {
                $.each(obj.files,function(j,file){
                    form_data.append('photo['+i+']', file);
                    })
                });
            form_data.append(form);
            form_data.append('file',file_data);
            alert(form_data);
            $.ajax({
                url:'post.php',
                cache:false,
                contentType:false,
                processData:false,
                async:false,
                data:form_data,
                type:'post',
                success:function(answ){
                    $('#result').html(answ);
                }
            })
        })
    })

我查看了其他类似的解决方案,但没有解决我的问题 抱歉我的英语不好。

您不需要手动执行此操作;如果您只是将 form 作为 DOMElement 提供给 FormData 构造函数,那么所有表单值都将自动包含给您。

另请注意,您应该挂钩到表单的 submit 事件,而不是提交按钮的 click 事件。您还应该删除 async: false 的使用,因为使用它是非常糟糕的做法。

综上所述,试试这个:

$('form').submit(function(e){
    e.preventDefault();
    var form_data = new FormData(this); 

    $.ajax({
        type: 'post',
        url: 'post.php',
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(answ){
            $('#result').html(answ);
        }
    })
})