Formspree:Ajax提交无法正常工作

我在我的页面上使用formspree作为单字段表单。 为了避免将我的用户重定向到默认的感谢页面,我正在尝试使用ajax提交表单并显示成功/错误消息。

但是,我的代码不起作用。 据我所知,消息不会出现。 我认为这与想要在我的按钮中显示的消息有关,而我的按钮是输入字段。

这是小提琴 ,这是代码:

HTML:

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!'; } } }); 

谢谢!

有一些错别字和对输入值如何工作的误解。 这是一个更新的小提琴 。

我看到的两个主要问题是:

  1. xhr.send没有一个紧密的括号
  2. 您无法使用innerHTML更改输入的文本(

    我是使用www.enformed.io做的,它只是作为formspree工作,但是开箱即用的重定向,效果很好。 还有一些有趣的function,如电子邮件自定义。