微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

表单在 FormData javascript

如何解决表单在 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?