通过 JQuery AJAX 一起发送表单数据和字符串数据?

2022-08-30 11:47:02

如何发布文件和输入字符串数据?例如,我有许多其他隐藏的输入数据,我需要将它们发送到服务器,FormData()

html,

<form action="image.php" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" multiple="" />
<input type="hidden" name="page_id" value="<?php echo $page_id;?>"/>
<input type="hidden" name="category_id" value="<?php echo $item_category->category_id;?>"/>
<input type="hidden" name="method" value="upload"/>
<input type="hidden" name="required[category_id]" value="Category ID"/>
</form>

使用下面的代码,我只设法发送文件数据,而不发送隐藏的输入数据。

jquery,

// HTML5 form data object.
var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); // page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID

fd.append("file", file_data);

$.ajax({
    url: 'add.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

服务器.php

print_r($_FILES);
print_r($_POST);

结果

Array
(
    [file] => Array
        (
            [name] => xxx.doc
            [type] => application/msword
            [tmp_name] => C:\wamp\tmp\php7C24.tmp
            [error] => 0
            [size] => 11776
        )

)

我想得到这个作为我的结果,

Array
(
    [file] => Array
        (
            [name] => xxx.doc
            [type] => application/msword
            [tmp_name] => C:\wamp\tmp\php7C24.tmp
            [error] => 0
            [size] => 11776
        )

)

Array
(
    [page_id] => 1000
    [category_id] => 12
    [method] => upload
    ...
)

可能吗?


答案 1
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
    fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
    fd.append(input.name,input.value);
});
$.ajax({
    url: 'test.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        console.log(data);
    }
});

添加了一个循环,并更改为 用于对象引用,以追加到 .for.serialize().serializeArray().each()FormData


答案 2

好吧,作为一个更简单的替代方案和更短的,你也可以这样做!

var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID

fd.append("file", file_data);

$.ajax({
    url: 'add.php?'+ other_data,  //<== just add it to the end of url ***
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});