AJAX如何序列化和发布元素中的所有表单元素

时间:2020-06-28 12:36:46

标签: javascript jquery ajax

我正在尝试序列化并发布所有可能来自

元素或来自任何其他元素(div,tr等)的表单元素。

简而言之,我的表单将来自以下任意一个:

<form id="frm1">
  Name: <input ...>
  Gender: <select ...>
  <input type="button" value="Submit" onClick="submitFormData('frm1')"/>
</form>

有时,我有html TABLE,因此其中不能有,因此我使用:

<table>
  <tr id="frm1">
    <td><input type...></td>
    <td><select...></td>
    <td><input type="button" value="Submit" onClick="submitFormData('frm1')"/></td>
  </tr>
  <tr id="frm2">
    <td><input type...></td>
    <td><select...></td>
    <td><input type="button" value="Submit" onClick="submitFormData('frm2')"/></td>
  </tr>
</table>

我似乎无法弄清楚如何从给定元素中拉出并序列化所有表单元素(输入,选择等)。

到目前为止我的代码:

const ERROR_TYPE_FATALERROR = 1;
const ERROR_TYPE_INPUTERROR = 2;
const ERROR_TYPE_GLOBALMESSAGE = 3;

function submitFormData(formid) {

  var formNode = document.getElementById(formid);

  $.ajax({
    type: 'POST',
    url: $(location).attr('href'),
    // data: jQuery('#' + formid + ' input').serialize(), // this works, but will only get <INPUT...>s
    data: formNode.serialize(), // this doesn't work
    dataType : "json",
  }).done(function(response) {

    // If we have response, then it's PHP that returned an error!
    if(response) {

      // error type
      switch (response.type) {

        case ERROR_TYPE_GLOBALMESSAGE:
          // unhide informational box (i.e. "Data saved!")
          $('#globalMessage').addClass('d-block');
          $('#globalMessagePH').empty();
          $('#globalMessagePH').append(response.message);

          break;

        case ERROR_TYPE_FATALERROR:
          // unhide form fatal error message box showing response.message
          $('#fatalError').addClass('d-block');
          $('#fatalErrorMessagePH').empty();
          $('#fatalErrorMessagePH').append(response.message);

          break;

        case ERROR_TYPE_INPUTERROR:
          // unhide form input error messages based on response.field
          break;

        default:
          // ...
      }
    }

    // Successful post, but not response came back !?
    else {
      console.error("Post sent, but no response came back!?");
    }
  }).fail(function(response) {
    console.error("Unknown Error!"); // not sure yet how I'd get here... ?
  });

}

我还曾尝试向所有表单元素添加“ data2post”类,以便获取发布所需的所有元素并对其进行序列化:

var formNode = document.getElementById(formid);
var formData = formNode.getElementsByClassName('data2post');
...
  data: formData.serialize()
...

但它不起作用: formData.serialize不是函数

从我的JS代码段中可以看到,我知道刚好

data: jQuery('#' + formid + ' input').serialize()

有效,但这只会得到。我需要能够获得所有表单元素,而不管类型(输入,选择,文本区域等)如何

即使为了这个目的,我还是可以同时问一下,考虑到你们看到我正在使用此Ajax,出于良好的实践,我是否应该在中获得response.type等。 fail()部分?不知道如何在PHP中执行此操作,这意味着触发失败。我所知道的是,如果我用JSON数据die()我的脚本,它将作为响应发送...

感谢您的帮助。

干杯,帕特

编辑:这是我的SELECT输入示例:

<tr id="row_1">
  <!-- STATUS -->
  <td class="text-nowrap">
    <select name="isActive" id="isActive" class="form-control pl-2" aria-label="Account Status" aria-describedby="isActiveReq" required>
      <option value="1"  selected>Enabled</option>
      <option value="0" >Disabled</option>
    </select>

    <!-- missing field: add 'is-invalid' to the <input>'s classes to show OR 'was-validated' to the form's classes -->
    <div id="isActiveReq" class="pl-1 invalid-feedback">
      This field is required! 
    </div>
  </td>
  <td><input type="button" name="btnSave" value="Save" onClick="submitFormData('row_1')"></td>
</tr>

2 个答案:

答案 0 :(得分:0)

尝试使用$('#frm1').serialize();

var data = $('#frm1').serialize();

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

答案 1 :(得分:0)

没有表单元素也可以,

克隆指定的id元素,可以是其div或其他任何值:

$('#myDiv').clone()

附加到form元素中:

$('<form>').append($('#myDiv').clone()).serialize();

下面是工作示例,几乎包括了元素的类型:

function getSerialize(id){

    let element = $("#"+id);

    // if you are using form element
    if( element.prop("tagName") === "FORM" ){
        var data = element.serialize();
    }

    // if your are using another elements
    else{
        var myInputs = element.clone();
        // this is the bug getting select box selected value when clone, so we have selected value in clone using this hack.
        element.find('select').each(function(i) {
            myInputs.find('select').eq(i).val($(this).val())
        })
        var data = $('<form>').append(myInputs).serialize();
    }

    // you can return 'data' variable from here.
    console.log(data);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Div Serialize</h1>
<div id="myDiv">
    <input type="text" name="name" placeholder="Name"><br><br>
    <select name="age" placeholder="Age">
        <option value="">Age</option>
        <option value="18+">18+</option>
    </select><br><br>
    <textarea name="about" placeholder="About"></textarea><br><br>
    <button onClick="getSerialize('myDiv')">Get Serialize</button>
</div>

<h1>Form Serialize</h1>
<form id="myDivForm" action="" onSubmit="return false;">
    <input type="text" name="name" placeholder="Name"><br><br>
    <select name="age" placeholder="Age">
        <option value="">Age</option>
        <option value="18+">18+</option>
    </select><br><br>
    <textarea name="about" placeholder="About"></textarea><br><br>
    <button onClick="getSerialize('myDivForm')">Get Serialize Form</button>
</form>

希望获得帮助。