【发布时间】:2021-08-29 14:01:24
【问题描述】:
使用Symfony Forms,生成的HTML如下所示:
<input type="text" id="form_name" name="form[name]">
<input type="email" id="form_email" name="form[email]">
<textarea id="form_message" name="form[message]"></textarea>
使用一点 JS 将条目转换为 JSON 并提交:
const contactForm = document.getElementById('contact-form');
contactForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const jsonData = JSON.stringify(Object.fromEntries(formData));
// handle submission...
})
JSON 发送到后端:
"{"form[name]":"John Doe","form[email]":"example@domain.com","form[message]":"Some message"}"
在我的控制器中(在 PHP 中)我将数据序列化为一个数组:$data = json_decode($request->getContent()); 问题是该数据的格式(如预期)如下:
["form[name]" => "John Doe", "form[email]" => "example@domain.com", "form[message]" => "Some message"];
有没有内置的方法可以得到下面的结果(无论是PHP还是JS)?
[ "name" => "John Doe", "email" => "example@domain.com", "message" => "Some message" ];
我研究过使用Serializer Component 没有成功,现在想知道我是否遗漏了什么,或者是否应该在提交之前在 JS 中修复数据。可能有内置解决方案吗?
【问题讨论】:
标签: javascript php symfony