如何解决表单在 FormData javascript
我正在尝试提交表单而不使用 AJAX 重定向。从答案中我看到了 [best](new URLSearchParams(new FormData(form).entries()); )我发现(我认为)不使用 jQuery 是:
const form = document.querySelector('form');
const data = Object.fromEntries(new FormData(form).entries());
我正在尝试在我的代码中应用此机制,但由于某种原因,我的 form
没有信息。我想我在它被记录之前调用了这个函数?但我不知道如何解决它。
我的代码(简化):
HTML(使用 React 和 Reactstrap):
<Reactstrap.Form id="commentform" />
<Reactstrap.Input type="textarea" rows={4}></Reactstrap.Input>
</Reactstrap.Form>
...
<Reactstrap.Button onClick={()=>setTimeout(()=>{this.postComment()},500)}>Post</Reactstrap.Button>
JS(在同一个 React 类中):
postComment=()=>{
let xhttp = new XMLHttpRequest();
const form = document.querySelector('#commentform'); //this gets the form properly
const data = Object.fromEntries(new FormData(form).entries()); //this doesn't return anything
xhttp.open("POST",'/postComment/',false); //don't mind the fact that this is synchronized,shouldn't matter
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //I in tutorials like W3S that this is required
xhttp.send('newcomment='+data);
}
任何帮助将不胜感激。
解决方法
来自MDN docs
注意:FormData 将仅使用使用 name 属性的输入字段。
尝试命名输入元素:
<Reactstrap.Input name="newcomment" type="textarea" rows={4}></Reactstrap.Input>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。