序列化选择

时间:2020-04-12 17:49:31

标签: javascript jquery serialization

我的表格(某处)

<form name="ShoppingCart" method="post">
  <select name="city">
    <option value="db5c88c4-391c-11dd-90d9-001a92567626">City1</option>
    <option value="db5c88c4-391c-11dd-90d9-001a92567636">City2</option>
    ...
    <option value="db5c88c4-391c-11dd-90d9-001a92567689">CityN</option>
  </select>
  <select name="warehouses">
    <option value="db5c88c4-391c-11dd-90d9-001a92567329">Warehouses1</option>
    <option value="db5c88c4-391c-11dd-90d9-001a92567452">Warehouses2</option>
    ...
    <option value="db5c88c4-391c-11dd-90d9-001a92567352">WarehousesN</option>
  </select>
  <div>
      <input class="submit_form" type="submit" name="Submit" value="Submit" />
  </div>
</form>

根据第一个选择的选择动态创建的选择仓库。 我需要serialize()形式,以便它是现值和序列化中的文本。

cityName=City1&cityValue=db5c88c4-391c-11dd-90d9-001a92567352&warehousesName=Warehouses1&warehousesValue=db5c88c4-391c-11dd-90d9-001a92567352

我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果要发布数据,则可以使用对象,也可以使用FormData。无论哪种方式,您都需要构建新结构,因为您的表格不包含这些项目。大多数人将使用“值”在服务器上所需的数据上查找数据,而不是将其发送到服务器。根据需要将最少的数据传递到服务器。

$(function() {
  $("form").submit(function(e) {
    e.preventDefault();
    var fData = {};
    // Alternate:
    var formD = new FormData();

    $("select", this).each(function(i, el) {
      fData[$(el).attr("name") + "Name"] = $("option:selected", el).text().trim();
      fData[$(el).attr("name") + "Value"] = $(el).val();
      // Alternate:
      formD.append($(el).attr("name") + "Name", $("option:selected", el).text().trim());
      formD.append($(el).attr("name") + "Value", $(el).val());
    });
    console.log($.param(fData));
    // FormData does not have a Serialize or Stringify method
    for (var pair of formD.entries()) {
      console.log(pair[0] + ': ' + pair[1]);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="ShoppingCart" method="post">
  <select name="city">
    <option value="db5c88c4-391c-11dd-90d9-001a92567626">City1</option>
    <option value="db5c88c4-391c-11dd-90d9-001a92567636">City2</option>
    <option value="db5c88c4-391c-11dd-90d9-001a92567689">CityN</option>
  </select>
  <select name="warehouses">
    <option value="db5c88c4-391c-11dd-90d9-001a92567329">Warehouses1</option>
    <option value="db5c88c4-391c-11dd-90d9-001a92567452">Warehouses2</option>
    <option value="db5c88c4-391c-11dd-90d9-001a92567352">WarehousesN</option>
  </select>
  <div>
    <input class="submit_form" type="submit" name="Submit" value="Submit" />
  </div>
</form>

如您所见,这将对select元素进行迭代并根据需要收集数据。然后,您需要将其发布到脚本中。