【发布时间】:2016-04-14 02:37:37
【问题描述】:
我正在将 formspree 用于我页面上的单字段表单。为了避免将我的用户重定向到默认的感谢页面,我尝试使用 ajax 提交表单并显示成功/错误消息。
但是,我的代码不起作用。据我所知,这些消息没有出现。我认为这与想要在我的按钮中显示的消息有关,而我的按钮是一个输入字段..
这是fiddle,这是代码:
HTML:
<div id="contactFormWrapper">
<form id="contact-form" action="http://formspree.io/myemail@gmail.com" method="POST">
<input type="message" name="name" value placeholder="Chanel Boy.." class="design--form">
<input id="send-button" type="submit" class="btn--main" style="width:auto" value="SUBMIT">
</form></div>
JS:
var contactForm = document.querySelector('#contact-form'),
inputName = contactForm.querySelector('[name="name"]'),
sendButton = contactForm.querySelector('#send-button');
sendButton.addEventListener('click', function(event){
event.preventDefault(); // prevent the form to do the post.
sendButton.innerHTML = 'Sending..';
var xhr = new XMLHttpRequest();
xhr.open('POST', '//formspree.io/myemail@gmail.com', true);
xhr.setRequestHeader("Accept", "application/json")
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(
"name=" + inputName.value;
xhr.onloadend = function (res) {
if (res.target.status === 200){
sendButton.innerHTML = 'Message sent!';
}
else {
sendButton.innerHTML = 'Error!';
}
}
});
谢谢!
【问题讨论】:
-
语法问题太多。 元素缺少属性 value="something"。 xhr.onloadend 应该在 xhr.send 之外。