你能提交一个带有文本输入数组的表单吗

can you submit a form with an array of text input?

本文关键字:输入 文本 数组 表单 一个 提交      更新时间:2023-09-26

我正在动态构建一个页面。此页面需要从输入标签中读取信息,但它是动态的。既然我在看,我应该把东西设置为数组吗

我想保留数据集。

<script>
   function adjustPilots(){
var pilots = $("#numPilots").val();
var info = '<td><table>'+
    '<tr><td>Minumum Collateral</td><td colspan="2"><input type = "text" size = "10" maxLength = "6" /> to <input type = "text" size = "10" maxLength = "6" /></td></tr>'+
    '<tr><td>Reward</td><td colspan="2"><input type = "text" size = "10" maxLength = "6" /> to <input type = "text" size = "10" maxLength = "6" /></td></tr>'+
    '<tr><td>Volume</td><td colspan="2"><input type = "text" size = "10" maxLength = "7" /> to <input type = "text" size = "10" maxLength = "7" /></td></tr>'+
    '<tr><td>Start: </td><td><input type = "text" name = "s" id = "s" class = "s" value autocomplete = "off"></td></tr>'+
    '<tr><td>End: </td><td><input type = "text" name = "e" id = "e" class = "e" value autocomplete = "off"></td></tr>'+
    '</table></td>';

for(var i = 0; i < Number(pilots); i++){
    $("#pilotrow").append(info);
}
}
</script>
<body>
<form>
<table>
<tr><td>Number of Pilots</td><td colspan="2"><input id = "numPilots" type = "text" size="3" maxLength="3" onchange = 'adjustPilots()' /></td></tr>
<tr id = "pilotrow"></tr>
<tr><td><input type = "submit" name = "submit"></td></tr>
</table>
</form>
</body>

我想的一个选择是不使用表单,而是用javascript构建它。然后创建一个JSON对象,并使用AJAX将其发送到服务器。这是一种可靠的方法吗,还是有更好的想法?

至少有两种方法可以做到这一点。

在没有javascript的情况下,您可以使用元素数组对表单进行排序,如以下

<input type="text" name="input[]"/>
<input type="text" name="input[]"/>
<input type="text" name="input[]"/>
<input type="text" name="input[]"/>

php中的

$inputs = $_POST['input'];
for($inputs as $inp){
}

使用ajax和jquery,您只需序列化表单并发布到后端

您可以通过在输入中使用name属性来实现这一点。像这样:

<input type="text" name="pilots[]" />

然后,您可能需要跟踪添加了多少导频,以便发送索引数组。像这样:

<input type="text" name="pilots[0][minumumCollatural]" />
<input type="text" name="pilots[0][reward]" />
<input type="text" name="pilots[0][volume]" />

这样,当你将表格提交到服务器时,你的飞行员阵列将看起来像:

$pilots = $_POST['pilots'];
// Which looks like
array(
   [0] => array
          (
             [minumumCollatural] => // Some number
             [reward] => // Some number
          )
    [1] => array
          (
             [minumumCollatural] => // Some number
             [reward] => // Some number
          )
)

尝试使用隐藏的输入标记以任何方式发送数据。例如:

<input type="hidden" name="myinput" id="myinput" />

现在在JS中:

$("form").submit(function() {
    $("input").not("#myinput").each(function() {
        $("#myinput").val($("#myinput").val()+$(this).val());
        // you can format anyway you want this is just an example
    });
});

希望这能有所帮助!