我目前正在构建一个表单,使用formspree向我的电子邮件发送消息。IO API,但我不理解js写的。我想让它在发送表单时显示#status
错误或成功消息。表单可以工作,但是消息没有显示
<div class="contact">
<div class="contact-content">
<div class="close">
<i class="fa fa-times" aria-hidden="true"></i>
</div>
<form action="https://formspree.io/f/xyylbnle" method="POST" id="contact-form">
<div class="form-group">
<input type="text" id="full-name" name="full-name" placeholder="Full Name" required>
</div>
<div class="form-group">
<input type="email" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<textarea id="message" name="message" cols="40" rows="5" placeholder="Send a message!" required></textarea>
</div>
<button class="primary-button submit">
Send
</button>
</form>
</div>
<div id="status" class="success">
Sent Successfully
</div>
</div>
这是给我的javascript从formspree
var form = document.getElementById("my-form");
async function handleSubmit(event) {
event.preventDefault();
var status = document.getElementById("my-form-status");
var data = new FormData(event.target);
fetch(event.target.action, {
method: form.method,
body: data,
headers: {
'Accept': 'application/json'
}
}).then(response => {
status.innerHTML = "Thanks for your submission!";
form.reset()
}).catch(error => {
status.innerHTML = "Oops! There was a problem submitting your form"
});
}
form.addEventListener("submit", handleSubmit)
这是我编辑的,使表单工作:
var form = document.getElementById("contact-form");
async function handleSubmit(event) {
event.preventDefault();
var status = document.getElementById("status");
var data = new FormData(event.target);
fetch(event.target.action, {
method: form.method,
body: data,
headers: {
'Accept': 'application/json'
}
}).then(success => {
status.classList.add('success')
status.innerHTML = "Successfully Sent";
form.reset()
}).catch(error => {
status.classList.add('error')
status.innerHTML = "Error"
});
}
form.addEventListener("submit", handleSubmit)
我第一次使用API
看下面几行:
var status = document.getElementById("my-form-status");
...
status.innerHTML = "Thanks for your submission!";
代码期望一个具有#my-form-status
的id
的元素。看起来你已经用#status
的id
编写了你的状态元素持有人,这样代码就找不到任何匹配的元素,并且不会像预期的那样工作。
说句题外话,我很惊讶这个表单能像你说的那样工作。你发布的JS中的第一行是:
var form = document.getElementById("my-form");
,但你的形式id
是#contact-form
。看起来应该是匹配的。