为什么我不能使用表单内的提交按钮发送数据

huangapple go评论97阅读模式
英文:

Why I can't send data using submit button inside Form

问题

我想创建一个带有表单的简单React组件,每次用户点击"提交"按钮时,数据应该发送到服务器。

出于测试目的,我创建了一个组件,其中包含两个按钮,一个独立存在,另一个位于表单内。

  1. return (
  2. <>
  3. <button onClick={submit}>Working example</button>
  4. <form style={cellStyle} onSubmit={submit}>
  5. <div>
  6. <input type="submit"
  7. value={reactDict["send"]}
  8. className="btn btn-success"
  9. style={{ margin: "15px 5px 5px 0px" }} />
  10. </div>
  11. </form>
  12. </>
  13. );

它们都使用相同的"submit"函数。

  1. const submit = (event) => {
  2. event.preventDefault();
  3. const requestOptions = {
  4. method: 'POST',
  5. headers: { 'Content-Type': 'application/json' },
  6. body: JSON.stringify({ test: 'some message' })
  7. };
  8. fetch('neededitems', requestOptions)
  9. .then(async response => {
  10. console.log(response);
  11. })
  12. .catch(error => {
  13. console.error('There was an error!', error);
  14. });
  15. }

当我点击表单外部的按钮时,一切正常工作,为什么我不能使用表单内的提交按钮发送数据

当我点击表单内部的"提交"按钮时,我收到了一个错误为什么我不能使用表单内的提交按钮发送数据

英文:

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.

  1. return (
  2. &lt;&gt;
  3. &lt;button onClick={submit}&gt;Working example&lt;/button&gt;
  4. &lt;form style={cellStyle}
  5. onSubmit={submit}&gt;
  6. &lt;div&gt;
  7. &lt;input type=&quot;submit&quot;
  8. value={reactDict[&quot;send&quot;]}
  9. className=&quot;btn btn-success&quot;
  10. style={{ margin: &quot;15px 5px 5px 0px&quot; }} /&gt;
  11. &lt;/div&gt;
  12. &lt;/form&gt;
  13. &lt;/&gt;
  14. );

Both of them use same "submit" function

  1. const submit = (event) =&gt; {
  2. event.preventDefault();
  3. const requestOptions = {
  4. method: &#39;POST&#39;,
  5. headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },
  6. body: JSON.stringify({ test: &#39;some message&#39; })
  7. };
  8. fetch(`neededitems`, requestOptions)
  9. .then(async response =&gt; {
  10. console.log(response);
  11. })
  12. .catch(error =&gt; {
  13. console.error(&#39;There was an error!&#39;, error);
  14. });
  15. }

When I click button outside form everything works fine 为什么我不能使用表单内的提交按钮发送数据,

When I click submit button inside form I got an error 为什么我不能使用表单内的提交按钮发送数据.

答案1

得分: 1

将属性method=&quot;post&quot;添加到<form>元素。

英文:

Add the attribute method=&quot;post&quot; to the <form> element.

huangapple
  • 本文由 发表于 2023年6月1日 22:46:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定