如何检查表单提交时 firebase 推送事件是否成功

How do I check if a firebase push event was successful on form submit

这是我的聚合物形式 javascript。它推得很好。我想做的是检查它是否成功,我将隐藏表单并显示一些确认文本或将用户重定向到另一个页面..,

那么,如何检查 firebase 推送是否成功?

<form is="iron-form" method="get" action="firebaseURL/events" id="eventsDemo">
  <paper-input name="name" label="Name" required auto-validate></paper-input>
  <paper-input name="password" label="Password" type="password" required auto-validate></paper-input>
  <paper-checkbox name="read" required>You must check this box</paper-checkbox><br>
  <paper-button raised onclick="_delayedSubmit(event)" disabled id="eventsDemoSubmit">
    <paper-spinner id="spinner" hidden></paper-spinner>Submit</paper-button>
  <div class="output"></div>
</form>   
<script>
function _delayedSubmit(event) {
    event.preventDefault();
    spinner.active = true;
    spinner.hidden = false;
    eventsDemoSubmit.disabled = true;
    // Simulate a slow server response.
    setTimeout(function() {
      //Polymer.dom(event).localTarget.parentElement.submit();
      var firebase = new Firebase(eventsDemo.getAttribute('action'));
      firebase.push(eventsDemo.serialize());
    }, 100);
  }
</script>

Firebase 中的每个写入方法都可以采用一个可选的完成侦听器,它将在服务器上完成写入操作时调用。来自 documentation on completion callbacks:

If you'd like to know when your data has been committed, you can add a completion callback. Both set() and update() take an optional completion callback that is called when the write has been committed to the database. If the call was unsuccessful for some reason, the callback will be passed an error object indicating why the failure occurred.

dataRef.set("I'm writing data", function(error) {
  if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});

我建议从头到尾阅读 Firebase guide for web programmers。它包含许多有用的花絮,可以为您(和我们)节省很多时间。

谢谢弗兰克!这是使用箭头函数对 ES6 的@Frank 答案的修改版本:

dataRef.set("I'm writing data", error => {
  if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});