通过ajax提交多个表单

时间:2018-05-27 21:41:57

标签: jquery ajax forms form-submit

我有一个while循环,重复事件的表单。表单运行mysql查询我试图使用ajax来阻止提交页面的重定向。我试图找出如何传递似乎不起作用的数据,因为每个表单具有相同的类或id。

image of the table with submit button for each row 表格

<form action="status_change.php" method="post" class="ajax">
      <div class="form-group"> 
           <input type="hidden" class="form-control"  name="incidentnum" value="' . $row_aincidents['incidentnumber'] . '">
</div>
<div class="form-group"> 
<input type="hidden" class="form-control"  name="unit" value="' . $row_aincidents['unitid'] . '">
 </div>
 <div class="form-group"> 
 <input type="hidden" class="form-control"  name="status" value="3">
 </div>

 <button type="submit" class="btn btn-primary btn-sm">STAMP</button>
 </form>

Java脚本

      $('form.ajax').on('submit', function () {

          var that = $(this),
                  url = that.attr('action'),
                  type = that.attr('metod'),
                  data = {};

          that.find('[name]').each(function (index, value) {
              var that = $(this),
                      name = that.attr('name'),
                      value = that.val();

              data[name] = value;

          });

          $.ajax({
              url: url,
              type: type,
              data: data,
              success: function(response) {
                  console.log(response);
              }
          });
          return false;
      });

1 个答案:

答案 0 :(得分:0)

我认为你只是有一些错别字和错误。您需要指定方法(并且您获得了表单属性的拼写错误)。您还要将方法设置为type选项。

jQuery ajax调用的默认方法是get,因此如果您通过post预期,则不会获得任何数据服务器端。

  $('form.ajax').on('submit', function () {

      var that = $(this),
          url = that.attr('action'),
          type = that.attr('method'),
          data = {};

      that.find('[name]').each(function (index, value) {
          var that = $(this),
              name = that.attr('name'),
              value = that.val();
          data[name] = value;
      });

      $.ajax({
          url: url,
          method: type,
          data: data,
          success: function(response) {
              console.log(response);
          }
      });

      return false;

  });

同样最好设置您期望从服务器返回哪种类型的返回数据。 $.ajax的默认预期数据类型是猜测(jQuery可以检测json,xml,html和脚本)。您可以使用dataType选项指定预期的数据类型。

在同一表单中输入具有相同名称的输入也不是一个好习惯。在你的情况下,因为你有多个表格,这不会是一个问题。

您可以详细了解$.ajax here