У меня есть простая настройка формы на моем статическом сайте gatsbyJS (с помощью formspree.io). Теперь я реализовал простой запрос AJAX вместо перенаправления пользователя на другую страницу.
В режиме разработки все работает отлично. Однако, как только я создаю и обслуживаю сайт, он каким-то образом возвращается к перенаправлению после отправки формы. Я просто не могу понять, что здесь не так, любая помощь будет очень признательна.
Вот моя форма:
<form id='myform' action="http://formspree.io/[email protected]" 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>
и вот мой Javascript:
if (typeof window !== `undefined`) {
document.addEventListener('DOMContentLoaded',function(){
var contactForm = document.querySelector('#myform'),
inputName = contactForm.querySelector('[name="name"]'),
inputEmail = contactForm.querySelector('[name="email"]'),
inputMessage = contactForm.querySelector('[name="message"]'),
sendButton = contactForm.querySelector('#send-button');
sendButton.addEventListener('click', function(event){
event.preventDefault(); // prevent the form to do the post.
sendButton.value = 'Sending..';
var xhr = new XMLHttpRequest();
xhr.open('POST', '//formspree.io/[email protected]', true);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onloadend = function (res) {
if (res.target.status === 200){
sendButton.value = 'Message sent! I will be in touch soon.';
contactForm.reset();
} else {
sendButton.value = 'Error!';
}
}
xhr.send("name=" + inputName.value + "email=" + inputEmail.value + "message=" + inputMessage.value);
});
});
}
window
равноundefined
? - person Aluan Haddad   schedule 27.01.2018fetch
. Он возьмет все, что вы разместили, и сократит его до 3 строк простого кода. - person Aluan Haddad   schedule 27.01.2018