英文:
Why I can't send data using submit button inside Form
问题
我想创建一个带有表单的简单React组件,每次用户点击"提交"按钮时,数据应该发送到服务器。
出于测试目的,我创建了一个组件,其中包含两个按钮,一个独立存在,另一个位于表单内。
return (
<>
<button onClick={submit}>Working example</button>
<form style={cellStyle} onSubmit={submit}>
<div>
<input type="submit"
value={reactDict["send"]}
className="btn btn-success"
style={{ margin: "15px 5px 5px 0px" }} />
</div>
</form>
</>
);
它们都使用相同的"submit"函数。
const submit = (event) => {
event.preventDefault();
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: 'some message' })
};
fetch('neededitems', requestOptions)
.then(async response => {
console.log(response);
})
.catch(error => {
console.error('There was an error!', error);
});
}
英文:
I want to create simple react component with form inside, every time that user click Submit button, data should be send to the server.
For testing purposes I created component with two buttons, one stand alone and one inside form.
return (
<>
<button onClick={submit}>Working example</button>
<form style={cellStyle}
onSubmit={submit}>
<div>
<input type="submit"
value={reactDict["send"]}
className="btn btn-success"
style={{ margin: "15px 5px 5px 0px" }} />
</div>
</form>
</>
);
Both of them use same "submit" function
const submit = (event) => {
event.preventDefault();
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ test: 'some message' })
};
fetch(`neededitems`, requestOptions)
.then(async response => {
console.log(response);
})
.catch(error => {
console.error('There was an error!', error);
});
}
答案1
得分: 1
将属性method="post"
添加到<form>元素。
英文:
Add the attribute method="post"
to the <form> element.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论