javascript - 使用 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);
});
解决方案
假设您的服务器端代码实际上需要一个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-type
header为application/x-www-form-urlencoded
推荐阅读
- android - Android NDK:内部错误:armeabi ABI 应该只有一个架构定义。成立:
- c# - 如何在 Xamarin for iOS 中显示具有不同导航的 viewController
- powershell - 没有源目录的复制项
- iis - 无法在本地运行 Kentico 解决方案
- c++ - 处理 C++ 继承时的最佳实践
- jmeter - 当我们增加用户数量时,为什么平均响应时间会减少?
- conv-neural-network - 如何在 PyTorch 中执行 sum pooling
- mysql - 从另一个文件调用回调?节点js快递
- python - 如何从 selenium 在 Chrome 中启用“allow-insecure-localhost”标志?
- python - 为什么 range() 函数比将项相乘以在嵌套列表中获取副本要慢?