为什么我的javascript表单没有提交?

时间:2016-06-02 08:58:35

标签: javascript jquery forms firebase

我正在创建一个表单,通过POST方法直接将文本字段中包含的数据注入firebase。

这是html表单的代码:

<form>
  <h5>From:</h5>
      <div class="row">
        <div class="six columns">
          <label for="fromName">Name</label>
          <input class="u-full-width" placeholder="Full Name" id="fromName">
        </div>
        <div class="six columns">
          <label for="fromContactNo">Contact No.</label>
          <input class="u-full-width" placeholder="08xxx" id="fromContactNo">
        </div>
      </div>
      <label for="fromAddress">Address</label>
      <textarea class="u-full-width" placeholder="Full Address" id="fromAddress"></textarea>

      <!-- break -->

      <h5>To:</h5>
      <div class="row">
        <div class="six columns">
          <label for="toName">Name</label>
          <input class="u-full-width" placeholder="Full Name" id="toName">
        </div>
        <div class="six columns">
          <label for="toContactNo">Contact No.</label>
          <input class="u-full-width" placeholder="08xxx" id="toContactNo">
        </div>
      </div>
      <label for="toAddress">Address</label>
      <textarea class="u-full-width" placeholder="Full Address" id="toAddress"></textarea>

      <!-- break -->
      <h5>Delivery Details:</h5>
      <div class="row">
          <div class="u-full-width">
              <label for="itemDesc">Item description</label>
              <textarea class="u-full-width" placeholder="Item Description here" id="itemDesc"></textarea>
            </div>
        </div>

        <!-- break -->
        </br>
      <button class="button-primary" id="add-order">Send</button>
    </form>

javascript函数如下:

$(document).ready(function(){
var $fromName = $('#fromName');
var $fromContactNo = $('#fromContactNo');
var $fromAddress = $('#fromAddress');
var $toName = $('#toName');
var $toContactNo = $('#toContactNo');
var $toAddress = $('#toAddress');
var $itemDesc = $('#itemDesc');
var $addOrder = $('#add-order');

$addOrder.on('click', function(){

    var newOrder = {
        "from": {
            "name": $fromName.val(),
            "phone_no": $fromContactNo.val(),
            "address": $fromAddress.val(),
        },
        "to": {
            "name": $toName.val(),
            "phone_no": $toContactNo.val(),
            "address": $toAddress.val(),
        },
        "item": $itemDesc.val(),
    };

    $.ajax({
      type: 'POST',
      url: 'https://myUrl.firebaseio.com/order.json',
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify(newOrder),
      success: function(data) {
        console.log("Order added!", data);
      }
    });
});
});

我试图弄乱表单并且找不到任何破坏它的东西。控制台也没有显示错误。

1 个答案:

答案 0 :(得分:2)

这里有两个问题。第一个是你挂钩button的点击事件。这意味着form提交仍在进行中。当发生这种情况时,页面会被有效地重新加载,因为您没有给出form任何action属性,这反过来又阻止了AJAX调用的完成。要解决此问题,您应始终挂钩submit的{​​{1}}事件并使用form停止默认提交。

其次,您只在页面加载时检索输入元素的preventDefault()属性。此时用户尚未与他们进行交互。相反,您应该在发送AJAX请求之前获取它们的值。

试试这个:

val()