表和ajax中的嵌入表单无法正常工作

时间:2019-01-18 08:12:06

标签: jquery html

我对表格内的表单有疑问。单独发布值即可。但是我试图使用ajax来捕获表单数据。我只能抓住第一个要素。我只是不知道这是否有可能

$('form.ajax').on('submit', function() {
  var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

  // Testing 
  console.log(that);
  console.log(url);
  console.log(type);
  console.log(data);
  console.log(name);

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

  $.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response) {}

  });
  return false;
});
<form id="form1" method="post" action="post.php" class="ajax">
  <input name="id_1" value="1" />
</form>
</td>
<td>
  <input form="form1" type="text" name="record_1" value="Scooby Doo" />
</td>

2 个答案:

答案 0 :(得分:1)

问题

that.find('[name]')

jQuery find方法找到匹配元素,这些匹配元素来自您要搜索的元素。

它不会找到属于该表单 但不在其 内的表单控件。

喜欢这个:

<input form="form1" type="text" name="record_1" value="Scooby Doo" >

…属于表单元素,但通过form 属性与之关联。


修正方法

您需要将表单中的字段与表单中字段合并。

执行此操作的通用方法是找到具有form属性的字段,这些属性与表单的id匹配,并将它们与您已有的字段组合起来。

var that = $(this); 
var fields_in_that = that.find("[name]");
var form_id = that.attr("id");
var fields_belonging_to_that = $(`[form="${form_id}"]`);
var all_fields = fields_in_that.add(fields_belonging_to_that);

您可以改为假设表行中的所有输入都是您想要的输入。

var that = $(this); 
var row = that.parents("tr"); // Likely to break if you nest tables. Don't nest tables.
var inputs = row.find("[name]");

可能是更好的方法

您也可能会忘记手动收集表单字段的所有数据,而只是让浏览器为您完成:

  var data = new FormData(this); // "this" is still the form object
  $.ajax({
    url: url,
    type: type,
    data: data,
    contentType: false, // These two lines stop jQuery for trying to be
    processData: false, // clever with FormData and breaking it
    success: function(response) {}
  });

答案 1 :(得分:-1)

这可能就是您想要的,合并表单中的元素和属性表单等于id的元素

$.merge(that.find('[name]'),$.find("[name][form="+that[0].id+"]"))

that.find('[name]').add($.find("[name][form="+that[0].id+"]"))