用ajax发布序列化表格数据

时间:2018-11-08 06:59:20

标签: jquery

我有这张表格

  <div class="tab-pane" id="trade">
  <br/>
  <div class="well">There are currently a total of <b>$traders traders</b> and this session has a total of <b>Ksh $total</b> you can earn this very minute.</div>
   <form class="form-horizontal" name="trade">
   <br/>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Telephone Number:</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="email" placeholder="Enter Telephone Number" name="telephone"  required/>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Id Number:</label>
      <div class="col-sm-10">
        <input type="number" class="form-control" id="email" placeholder="Enter Id Number" name="nid"  required/>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Amount:</label>
      <div class="col-sm-10">
        <input type="number" class="form-control" id="email" placeholder="Enter Amount" name="amount"  required/>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Direction:</label>
      <div class="col-sm-10">
       <select class="form-control" name="direction"><option value="up">Up</option><option value="down">Down</option></select>
      </div>
    </div>
    <div class="form-group">        
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-success pull-right">Submit</button>
      </div>
    </div>
  </form>
  </div>

我将它作为我的jquery

 $(document).ready(function(){

  var datastring = $("#trade").serialize();
   $.ajax({
    type: "POST",
    url: "http://localhost/lords/trade.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
       alert(data);
    },
    error: function() {

    }
    });

   });

但是,我没有停止默认操作,并且重新加载了表单并且没有任何数据发布。

我已经尝试过了

var frm = $('#trade');
    frm.submit(function (ev) {
        $.ajax({
            type: 'post',
            url: 'http://localhost/lords/trade.php',
            data: frm.serialize(),
            success: function (data) {
                alert(data);
            }
        });
        ev.preventDefault();
    });

但这不会发布数据。我正在使用jQuery 3.3.1

这是小提琴https://jsfiddle.net/e3zc1gpb/3/

1 个答案:

答案 0 :(得分:0)

在表单标签上添加id =“ name”, 更改

var frm = $('#trade'); 

var frm = $('form[name="trade"]')