Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

reactjs - Form does not have data in FormData javascript

I'm trying to submit a form without redirecting using AJAX. From the answers I saw the [best](new URLSearchParams(new FormData(form).entries()); ) I found (I think) without using jQuery was:

const form = document.querySelector('form');
const data = Object.fromEntries(new FormData(form).entries());

I'm trying to apply this mechanism in my code, but for some reason my form does not have information. I guess I'm calling the function before it gets recorded? But I'm not sure how to fix it.

My code (simplified):

HTML (using React and 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 (inside the same React class):

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);
}

Any help would be appreciated.

question from:https://stackoverflow.com/questions/65945360/form-does-not-have-data-in-formdata-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From MDN docs

Note: FormData will only use input fields that use the name attribute.

Try naming the input element:

<Reactstrap.Input name="newcomment" type="textarea" rows={4}></Reactstrap.Input>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...