我设法使用Formik按预期配置所有内容,并且AJAX请求似乎很好(如果我启用它会向我显示成功消息),但Netlify表单部分仍为空(即使表单由Netlify列出并确认)。
这是我的联系人组件:
(我认为问题出在onSubmit函数下的ajax代码中)
import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import Layout from "../components/layout"
import SEO from "../components/seo"
const ContactForm = () => (
<Layout>
<SEO title="Form with Formik" />
<main class="page-contact-form">
<h1>Do your booking</h1>
<Formik
initialValues={{ email: '', name: '', start: '', end: '', message: '' }}
validate={values => {
let errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
) {
errors.email = 'Invalid email address';
}
return errors;
}}
onSubmit={(values) => {
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: ({
"form-name": "contact",
...values
})
}).then(() => alert("Thank you!"))
}}
>
{({ isSubmitting }) => (
<Form name="contact" data-netlify="true" action="/grazie">
<input type="hidden" name="form-name" value="contact" />
<label>Name and Surname: <br />
<Field type="text" name="name" placeholder="Nome Cognome" />
<ErrorMessage name="name" component="div" />
</label>
<br />
<label>Email: <br />
<Field type="email" name="email" placeholder="Richiesto" />
<ErrorMessage name="email" component="div" />
</label>
<br />
<label>Start and End <br />
<Field type="date" name="start" />
<ErrorMessage name="start" />
<Field type="date" name="end" />
<ErrorMessage name="end" />
</label>
<br />
<label>
Message: <br />
<Field type="text" name="message" />
<ErrorMessage name="message" />
</label>
<br />
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
</Formik>
</main>
</Layout>
)
export default ContactForm
在onsubmit
的fetch函数中,看起来你正在发送一个对象,但内容类型是url编码的?也许您需要先将对象序列化为url编码格式。 There's a host of solutions for that in this question。如果你提出最佳建议:
// https://stackoverflow.com/a/1714899/10340970
const serialize = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
...
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: serialize({
"form-name": "contact",
...values
})