如何在没有ajax的情况下在流星中提交带有post方法的表单?

时间:2014-11-24 20:44:42

标签: javascript forms post meteor

我对meteor的理解是表单提交不需要ajax,但是我想知道如何处理Template.form.event提交表单事件并在javascript中进行POST休息提交以便页面不会继续它只是发送数据并停留在页面上的操作目标。如何在没有ajax的情况下在javascript中进行POST。我假设有一个明显的答案,似乎无法想到它。我是否需要安装休息包。

我不希望运行表单操作,但是传递到javascript并通过POST发送,而不刷新METEOR中的页面。

这是表格

<form accept-charset="UTF-8" action="https://formkeep.com/f/randomnumbers" method="POST" id="contact-form">
  <input type="hidden" name="utf8" value="✓">

  <input type="text" placeholder="Name">


  <input type="phone" placeholder="Phone Number">


  <input type="email" placeholder="Your Email">

  </form>

1 个答案:

答案 0 :(得分:1)

您认为不需要使用AJAX来执行表单请求提交是正确的,您应该使用Meteor DDP协议,而不是使用Meteor方法。

首先,定义您的Meteor方法以执行所需的操作,这是一个示例:

Meteor.methods({
  addContact: function(contact){
    check(contact, {
      name: String,
      phoneNumber: String,
      email: String
    });
    //
    return Contacts.insert(contact);
  }
});

在检查参数格式是否正确后,此方法只是将一个联系人添加到集合中。

接下来,您需要在表单提交事件处理程序中调用此方法,如下所示:

Template.myForm.events({
  "submit": function(event, template){
    // prevent default form submission handler : which is
    // performing an HTTP POST request that will reload the page
    event.preventDefault();
    // construct the contact object that will be passed to the method
    var contact = {
      // assuming each input fields have ids attribute
      name: template.$("#name").val(),
      phoneNumber: template.$("#phoneNumber").val(),
      email: template.$("#email").val(),
    };
    // perform the server-side asynchronous call
    Meteor.call("addContact",contact);
  }
});