【问题标题】:Formspree: Ajax submit not workingFormspree:Ajax 提交不起作用
【发布时间】: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 之外。

标签: jquery ajax forms


【解决方案1】:

存在一些拼写错误和对输入值如何工作的误解。这是更新的fiddle

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

  1. xhr.send 没有右括号
  2. 您不能使用innerHTML更改输入(&lt;input type="submit&gt;)的文本,您需要更改valuesendButton.value = 'Sending...';

当我输入我的电子邮件地址而不是您的电子邮件地址时,这绝对对我有用。我收到了来自 formspree 的确认电子邮件,然后能够通过 fiddle 提交给自己。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 2017-08-09
    • 2013-04-09
    • 2017-07-03
    • 2016-04-06
    相关资源
    最近更新 更多