156

我正在使用 ajax 提交包含数组、文本字段和文件的多部分表单。

我将每个 VAR 附加到主数据中

var attachments = document.getElementById('files'); 
var data= new FormData();

for (i=0; i< attachments.files.length; i++){
    data.append('file', attachments.files[i]);
    console.log(attachments.files[i]);

    data.append ('headline', headline);
    data.append ('article', article);
    data.append ('arr', arr);
    data.append ('tag', tag);

然后我使用 ajax 函数将其发送到 PHP 文件以存储在 sql DB 中。

$.ajax({    
    type: "post",
    url: 'php/submittionform.php',
    cache: false,
    processData: false,
    contentType: false,
    data: data,
    success: function(request) {$('#box').html(request); }
})

但在 PHP 端,arr作为数组的变量显示为字符串。

当我不使用 ajax 将它作为表单数据发送但使用简单$.POST选项时,我确实将它作为 PHP 端的数组获取,但是我也无法发送文件。

任何解决方案?

4

13 回答 13

334

你也可以通过FormData这种方式发送一个数组:

var formData = new FormData;
var arr = ['this', 'is', 'an', 'array'];

for (var i = 0; i < arr.length; i++) {
  formData.append('arr[]', arr[i]);
}

console.log(...formData);

arr[]因此,您可以像使用简单的 HTML 表单一样编写代码。如果是 PHP,它应该可以工作。

您可能会发现这篇文章很有用:如何在查询字符串中传递数组?

于 2015-02-10T14:59:16.603 回答
135

你有几个选择:

将其转换为 JSON 字符串,然后在 PHP 中解析(推荐)

JS

var json_arr = JSON.stringify(arr);

PHP

$arr = json_decode($_POST['arr']);

或者使用@Curios 的方法

通过 发送数组FormData


不推荐:使用序列化数据,然后在 PHP 中反序列化

JS

// Use <#> or any other delimiter you want
var serial_arr = arr.join("<#>"); 

PHP

$arr = explode("<#>", $_POST['arr']);
于 2013-04-19T11:59:51.100 回答
13

打字稿版本:

export class Utility {      
    public static convertModelToFormData(model: any, form: FormData = null, namespace = ''): FormData {
        let formData = form || new FormData();
        let formKey;

        for (let propertyName in model) {
            if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
            let formKey = namespace ? `${namespace}[${propertyName}]` : propertyName;
            if (model[propertyName] instanceof Date)
                formData.append(formKey, model[propertyName].toISOString());
            else if (model[propertyName] instanceof Array) {
                model[propertyName].forEach((element, index) => {
                    const tempFormKey = `${formKey}[${index}]`;
                    this.convertModelToFormData(element, formData, tempFormKey);
                });
            }
            else if (typeof model[propertyName] === 'object' && !(model[propertyName] instanceof File))
                this.convertModelToFormData(model[propertyName], formData, formKey);
            else
                formData.append(formKey, model[propertyName].toString());
        }
        return formData;
    }
}

使用:

let formData = Utility.convertModelToFormData(model);
于 2018-03-20T05:25:53.763 回答
8

这是一个老问题,但我最近在发布对象和文件时遇到了这个问题。我需要能够发布一个对象,其子属性也是对象和数组。

下面的函数将遍历一个对象并创建正确的 formData 对象。

// formData - instance of FormData object
// data - object to post
function getFormData(formData, data, previousKey) {
  if (data instanceof Object) {
    Object.keys(data).forEach(key => {
      const value = data[key];
      if (value instanceof Object && !Array.isArray(value)) {
        return this.getFormData(formData, value, key);
      }
      if (previousKey) {
        key = `${previousKey}[${key}]`;
      }
      if (Array.isArray(value)) {
        value.forEach(val => {
          formData.append(`${key}[]`, val);
        });
      } else {
        formData.append(key, value);
      }
    });
  }
}

这将转换以下 json -

{
  name: 'starwars',
  year: 1977,
  characters: {
    good: ['luke', 'leia'],
    bad: ['vader'],
  },
}

进入以下FormData

 name, starwars
 year, 1977
 characters[good][], luke
 characters[good][], leia
 characters[bad][], vader
于 2017-03-29T18:54:45.537 回答
5

将所有类型输入添加到 FormData

const formData = new FormData();
for (let key in form) {
    Array.isArray(form[key])
        ? form[key].forEach(value => formData.append(key + '[]', value))
        : formData.append(key, form[key]) ;
}
于 2018-10-25T09:01:08.677 回答
3

这是另一个版本,convertModelToFormData因为我需要它也能够发送文件。

实用程序.js

const Utility = {
  convertModelToFormData(val, formData = new FormData, namespace = '') {
    if ((typeof val !== 'undefined') && val !== null) {
      if (val instanceof Date) {
        formData.append(namespace, val.toISOString());
      } else if (val instanceof Array) {
        for (let i = 0; i < val.length; i++) {
          this.convertModelToFormData(val[i], formData, namespace + '[' + i + ']');
        }
      } else if (typeof val === 'object' && !(val instanceof File)) {
        for (let propertyName in val) {
          if (val.hasOwnProperty(propertyName)) {
            this.convertModelToFormData(val[propertyName], formData, namespace ? `${namespace}[${propertyName}]` : propertyName);
          }
        }
      } else if (val instanceof File) {
        formData.append(namespace, val);
      } else {
        formData.append(namespace, val.toString());
      }
    }
    return formData;
  }
}
export default Utility;

我的客户端代码.js

import Utility from './utility'
...
someFunction(form_object) {
  ...
  let formData = Utility.convertModelToFormData(form_object);
  ...
}
于 2020-09-11T03:23:18.480 回答
2

如果您有嵌套对象和数组,则填充 FormData 对象的最佳方法是使用递归。

function createFormData(formData, data, key) {
    if ( ( typeof data === 'object' && data !== null ) || Array.isArray(data) ) {
        for ( let i in data ) {
            if ( ( typeof data[i] === 'object' && data[i] !== null ) || Array.isArray(data[i]) ) {
                createFormData(formData, data[i], key + '[' + i + ']');
            } else {
                formData.append(key + '[' + i + ']', data[i]);
            }
        }
    } else {
        formData.append(key, data);
    }
}
于 2019-02-20T14:44:16.647 回答
2

基于@YackY 回答较短的递归版本:

function createFormData(formData, key, data) {
    if (data === Object(data) || Array.isArray(data)) {
        for (var i in data) {
            createFormData(formData, key + '[' + i + ']', data[i]);
        }
    } else {
        formData.append(key, data);
    }
}

使用示例:

var data = {a: '1', b: 2, c: {d: '3'}};
var formData = new FormData();
createFormData(formData, 'data', data);

发送数据:

data[a]=1&
data[b]=2&
data[c][d]=3
于 2019-07-21T01:47:31.130 回答
2

下一个版本适用于包含一系列简单值的模型:

function convertModelToFormData(val, formData = new FormData(), namespace = '') {
    if((typeof val !== 'undefined') && (val !== null)) {
        if(val instanceof Date) {
            formData.append(namespace, val.toISOString());
        } else if(val instanceof Array) {
            for(let element of val) {
                convertModelToFormData(element, formData, namespace + '[]');
            }
        } else if(typeof val === 'object' && !(val instanceof File)) {
            for (let propertyName in val) {
                if(val.hasOwnProperty(propertyName)) {
                    convertModelToFormData(val[propertyName], formData, namespace ? namespace + '[' + propertyName + ']' : propertyName);
                }
            }
        } else {
            formData.append(namespace, val.toString());
        }
    }
    return formData;
}
于 2018-06-21T15:29:41.013 回答
1

将三种格式的 Data 转换为 FormData

1. 单个值,如字符串、数字或布尔值

 let sampleData = {
  activityName: "Hunting3",
  activityTypeID: 2,
  seasonAssociated: true, 
};

2. 数组是对象数组

let sampleData = {
   activitySeason: [
    { clientId: 2000, seasonId: 57 },
    { clientId: 2000, seasonId: 57 },
  ],
};

3. 持有键值对的对象

let sampleData = {
    preview: { title: "Amazing World", description: "Here is description" },
};

使我们的生活变得轻松的那些:

function transformInToFormObject(data) {
  let formData = new FormData();
  for (let key in data) {
    if (Array.isArray(data[key])) {
      data[key].forEach((obj, index) => {
        let keyList = Object.keys(obj);
        keyList.forEach((keyItem) => {
          let keyName = [key, "[", index, "]", ".", keyItem].join("");
          formData.append(keyName, obj[keyItem]);
        });
      });
    } else if (typeof data[key] === "object") { 
      for (let innerKey in data[key]) {
        formData.append(`${key}.${innerKey}`, data[key][innerKey]);
      }
    } else {
      formData.append(key, data[key]);
    }
  }
  return formData;
}

示例:输入数据

let sampleData = {
  activityName: "Hunting3",
  activityTypeID: 2,
  seasonAssociated: true,
  activitySeason: [
    { clientId: 2000, seasonId: 57 },
    { clientId: 2000, seasonId: 57 },
  ],
  preview: { title: "Amazing World", description: "Here is description" },
};

输出表格数据:

activityName: Hunting3
activityTypeID: 2
seasonAssociated: true
activitySeason[0].clientId: 2000
activitySeason[0].seasonId: 57
activitySeason[1].clientId: 2000
activitySeason[1].seasonId: 57
preview.title: Amazing World
preview.description: Here is description
于 2021-01-13T18:30:30.837 回答
1

我已经修复了打字稿版本。对于 javascript,只需删除类型定义。

  _getFormDataKey(key0: any, key1: any): string {
    return !key0 ? key1 : `${key0}[${key1}]`;
  }
  _convertModelToFormData(model: any, key: string, frmData?: FormData): FormData {
    let formData = frmData || new FormData();

    if (!model) return formData;

    if (model instanceof Date) {
      formData.append(key, model.toISOString());
    } else if (model instanceof Array) {
      model.forEach((element: any, i: number) => {
        this._convertModelToFormData(element, this._getFormDataKey(key, i), formData);
      });
    } else if (typeof model === 'object' && !(model instanceof File)) {
      for (let propertyName in model) {
        if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
        this._convertModelToFormData(model[propertyName], this._getFormDataKey(key, propertyName), formData);
      }
    } else {
      formData.append(key, model);
    }

    return formData;
  }
于 2021-01-27T22:34:34.827 回答
0

就我而言,我得到了

{
    "category": [
        "Incorrect type. Expected pk value, received str."
    ]
}

错误所以

对于谁使用 React(前端)和 Django DRF(后端):


const category = [1,2,3,4,5]
formData.append("category", JSON.stringify(category));

import json
from .serializers import ArticleSerializer
from rest_framework.response import Response

class ArticleListCreateView(ListCreateAPIView):
    permission_classes = (
        IsSuperuserOrReadOnly,
        IsAutherOrReadOnly,
    )
    serializer_class = ArticleSerializer
    model = Article
    queryset = Article.objects.filter(article_honor='a', status='p')


    def create(self, request, *args, **kwargs):
        data = request.data
        article = Article('set all argumenst')
        
        image = request.data['image']
        # save image in local

        article.save()
        categorys = json.loads(data['category'])
        for catID in categorys:
            cat = Category.objects.get(id=catID)
            article.category.add(cat)

        article.save()

        return Response(ArticleSerializer(article).data)


于 2022-02-01T12:38:11.603 回答
0

JavaScript 代码:

var formData = new FormData();
let arr = [1,2,3,4];
formData.append('arr', arr);

php上的输出:

$arr = $_POST['arr']; ===>  '1,2,3,4'

解决方案php代码:

$arr = explode(",", $_POST['arr']); ===> [1,2,3,4]
于 2021-11-24T14:27:34.557 回答