簡體   English   中英

將表單數據序列化為 json 反應

[英]Serialize form data to json react

我如何在反應中序列化數據?

<form method="post" action="/insert" onSubmit={(e)=>this.addMysql(e)}>
    <label>Username</label>
    <input type="text" id="username" name="nameUser"/>
    <label>Password</label>
    <input type="text" id="password" name="passs"/>
    <button type="submit" type="submit">Dodaj</button>
</form>

這是我的功能

addMysql(event){
    console.log(event.targe) //this outputs an empty form
    event.preventDefault();
}

我不想使用狀態。 只需 onSubmit 將所有表單數據發送到 AddMysql

https://medium.com/@snirlugassy/generic-input-handler-with-react-js-44a97e22cd0d

謝謝 Sag1v

我建議你使用states ,因為那是Reacty的方式。 如果沒有,我可能會提出一些建議。

通常我會建議使用FormData API,但IE和舊版瀏覽器不支持它。

我認為這個答案應該能讓你繼續前進,因為它是serialize的普通 JS 版本。

如果您使用的是jQuery ,則最后進行serialize ,我認為您不是或者您不應該這樣做。

//So, here's a simple trick i use to get this done: //Using React Hook const [data, setData] = useState({}); //the create an onInputChange function for the Inputs this way const onInputChange = async e =>{ const {name, value} = e.target; //check to validate if entry is not a number if(isNaN(name)){ data[name] = value; //somehow update data setData({...data}) } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM