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

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

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 (
    &lt;&gt;
    &lt;button onClick={submit}&gt;Working example&lt;/button&gt;
    &lt;form style={cellStyle}
        onSubmit={submit}&gt;
                
        &lt;div&gt;
            &lt;input type=&quot;submit&quot;
                value={reactDict[&quot;send&quot;]}
                className=&quot;btn btn-success&quot;
                style={{ margin: &quot;15px 5px 5px 0px&quot; }} /&gt;
        &lt;/div&gt;
    &lt;/form&gt;
    &lt;/&gt;
);

Both of them use same "submit" function

const submit = (event) =&gt; {
    event.preventDefault();
    const requestOptions = {
        method: &#39;POST&#39;,
        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },
        body: JSON.stringify({ test: &#39;some message&#39; })
    };

    fetch(`neededitems`, requestOptions)
        .then(async response =&gt; {
            console.log(response);
        })
        .catch(error =&gt; {
            console.error(&#39;There was an error!&#39;, error);
        });
}

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:

确定