gpt4 book ai didi

javascript - 序列化选择

转载 作者:行者123 更新时间:2023-12-02 21:08:02 26 4
gpt4 key购买 nike

我的表格(大约)

<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

我怎样才能做到这一点?

最佳答案

如果您要发布数据,则可以使用对象或可以使用 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 元素并根据您的需要收集数据。然后您需要将其发布到您的脚本中。

关于javascript - 序列化选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61175734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com