我在静态gatsbyJS网站上设置了一个简单的表单(使用formspree.io)。现在我实现了一个简单的AJAX请求,而不是将用户重定向到另一个页面。
在开发模式下,它们完全正常。一旦我建立并服务该网站,它在提交表单后会以某种方式回退到重定向。我无法弄清楚这里有什么不对,任何帮助都会非常感激。
这是我的表格:
diagonals = lambda x,y:[(x-1, y-1), (x-1,y+1), (x+1,y-1), (x+1,y+1)]
horiz_vert= lambda x,y:[(x,y+1), (x,y-1), (x+1,y), (x-1,y)]
这是我的Javascript:
<form id='myform' action="http://formspree.io/testmail@gmail.com" method="POST">
<div className="formgroup">
<input id='name' type="text" name="name" placeholder='Name'/>
<input id='email' type="email" name="email" placeholder='Email'/>
</div>
<div className="formfield">
<textarea id='message' name="message" rows='6' placeholder='Message'/>
</div>
<div className="formfield">
<input id='send-button' type="submit" value="Send"/>
</div>
</form>
答案 0 :(得分:2)
在指向正确的方向后,我开始工作..
我使用了https://www.snip2code.com/Snippet/1613019/formspree-with-fetch/中的代码段并稍微修改了一下,以便在提交时更改按钮文字。它在gatsbyjs站点的构建环境中完美运行:
if (typeof window !== `undefined`) {
window.onload=function(){
const sendButton = document.getElementById('send-button')
const formDataToJson = formData => {
const entries = formData.entries();
const dataObj = Array.from(entries).reduce( (data, [key, value]) => {
data[key] = value;
if (key === 'email') {
data._replyTo = value;
}
return data;
}, {});
return JSON.stringify(dataObj);
};
const postToFormspree = formData => fetch(`https://formspree.io/youremail@gmail.com`, {
method: 'POST',
body: formDataToJson(formData),
headers: {
'Content-Type': 'application/json'
}
}).then(r => r.json());
document.getElementById('myform').addEventListener('submit', function (e) {
e.preventDefault();
sendButton.value = 'Sending..';
const formData = new FormData(this);
postToFormspree(formData).then(response => {
sendButton.value = 'Message sent!';
myform.reset();
});
});
}
}