首页 > 解决方案 > 使用 formData() 提交多个输入

问题描述

我想使用 AJAX 请求并能够提交多个输入,所以我为此使用 FormData。

我不知道如何附加多个具有相同名称的输入(“name []”)。我尝试了这种方法,但不知何故它不起作用。我不知道什么是正确的方法,我一直在尝试很多方法,但它就是行不通。感谢提前!

<input type="text" name="test[]">

let formData = new FormData();
formData.append('test[0]',1);
formData.append('test[1]',2);
formData.append('test[2]',3);

axios({
    method:'post',
    url:'url',
    data:formData,
    config:{headers:{'Content-Type':'multipart/form-data'}}
}).then(function(response){
    console.log(response);      
});

标签: javascriptaxiosform-data

解决方案


假设您的服务器端代码实际上需要一个application/x-www-form-urlencoded请求正文而不是multipart/form-data,请尝试这样的事情

axios.post('url', new URLSearchParams([
  ['test[]', 1],
  ['test[]', 2],
  ['test[]', 3]
])).then(response => console.log(response))

URLSearchParams被序列化为字符串格式时,它就像

"test%5B%5D=1&test%5B%5D=2&test%5B%5D=3"

而axios会自动设置Content-typeheader为application/x-www-form-urlencoded


推荐阅读