javascript - 如何将输入数据和复选框从表单发送到服务器?
问题描述
useEffect(() => {
if(readyToSend){
let data = {
"email":"example.org",
"newsletter": true
};
let jsonData = JSON.stringify(data);
let encodedData = encodeURIComponent(jsonData);
let url = "https://example/receiver/external"
let fetchUrl = url + "?datajsonstr=" + encodedData + "&_=" + (new Date()).valueOf();
let datafetch = fetch(fetchUrl);
datafetch.then(data => {
props.setDataDone(true)
})
}})
我不想硬编码我的代码中的值。这些值可能来自 Form (TextField)。
解决方案
您需要将输入的值存储在状态中,以便在提交表单时可以对状态进行字符串化,并将其上传到您的服务器。
这是一个带有模拟 API 的工作版本,这是代码。
const { useState } = React;
function mockApi(data) {
return new Promise((res, rej) => {
setTimeout(() => res(`${data} stored`), 2000);
});
}
function Example() {
// Set state as an object
const [ form, setForm ] = useState({});
// When the form is submitted call the API endpoint
// with the JSON
async function handleSubmit(e) {
e.preventDefault();
const msg = await mockApi(JSON.stringify(form));
console.log(msg);
}
// Every time an input's value changes,
// update the state
function handleChange(e) {
const { name, value } = e.target;
setForm({ ...form, [name]: value });
}
return (
<form onSubmit={handleSubmit} onChange={handleChange}>
<input type="text" name="name" required />
<input type="password" name="password" required />
<button type="submit">Submit</button>
</form>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
推荐阅读
- python - 从矩阵列表中删除重复矩阵
- android - 在 kotlin 中上传文件时出现内存不足错误
- clockify - 在 Clockify 中自动生成报告
- sql-server - 如何将英尺和英寸组合成一个组合列
- sqlalchemy - Airflow + sqlalchemy 与元数据数据库的短暂连接
- r - Shiny R - 使用 observeEvent 和 updateVarSelection 时,下拉列表不断重置为列表中的第一个
- python - 在 Python3 中将 UTF-8 字符串转换为 CP860
- python - 你如何解压缩不同长度的嵌套列表?
- svg - 如何通过避免多余的 SVG 元素来应用 SVG 过滤器 feGaussianBlur?
- java - 复制数组列表中的项目