【问题标题】:PHP - dynamic fields array notPHP - 动态字段数组不是
【发布时间】:2017-02-06 23:12:06
【问题描述】:

我有一个带有动态字段的表单。当我添加一个动态字段并对该字段执行var_dump 时,我只得到第一个结果。

表格:

<div class="form-group halltype">
    <label class="col-sm-2 col-sm-2 control-label">HallType</label>
    <div class="col-sm-10">
        <input type="text" class="form-control" name="title1[]" placeholder="Main Title"><br />
        <input type="text" class="form-control" name="title2[]" placeholder="Title 2"><br />
        <input type="text" class="form-control" name="seating[]" placeholder="Seating Capacity"><br />
        <input type="text" class="form-control" name="floating[]" placeholder="Floating Capacity"><br />
    </div>
</div>
<div class="form-group addhalltype">
    <label class="col-sm-2 col-sm-2 control-label"></label>
    <div class="col-sm-10">                        
        <input type="button" class="btn btn-info" id="">Add Hall Type</button>
    </div>

jquery:

$(".addhalltype").click(function() {
    $halltype = '<div class="form-group halltype"><label class="col-sm-2 col-sm-2 control-label">HallType</label><div class="col-sm-10"><input type="text" class="form-control" name="title1[]" placeholder="Main Title"><br /><input type="text" class="form-control" name="title2[]" placeholder="Title 2"><br /><input type="text" class="form-control" name="seating[]" placeholder="Seating Capacity"><br /><input type="text" class="form-control" name="floating[]" placeholder="Floating Capacity"><br /></div></div>';
    $($halltype).insertBefore(".addhalltype");
});

如果我这样做var_dump($_POST['title1']),我会得到

array(1) {
  [0]=>
  string(4) "1212"
}

【问题讨论】:

  • 在表单中使用动态字段时,如果您想在数组中返回多个元素,请在所有标题元素上使用类似 name='title[]' 的内容,然后当您 vardump $_POST['title']你会得到一个包含所有项目的数组
  • 我也没有看到 &lt;form&gt; 元素,并且我还假设您正在将此“表单”发布到您正在 var_dumping / 处理响应的 php 页面

标签: php jquery arrays forms dynamic


【解决方案1】:

您在 var_dump 中打印 $_POST['title1'] 它只会显示您为 name="title1[]" 插入的值。

这里您使用的是动态数组,但名称不同,即名称等于 title1[] title1[] seat[] 和 floating[]。

如果您想以一个名称(如 title[0],title[1],...title[n])获取所有帖子值以获取这种格式的结果,您必须使用这种格式编写上述代码.

 <input type="text" class="form-control" name="title[]" placeholder="Main Title"><br />
    <input type="text" class="form-control" name="title[]" placeholder="Title 2"><br />
    <input type="text" class="form-control" name="title[]" placeholder="Seating Capacity"><br />
    <input type="text" class="form-control" name="title[]" placeholder="Floating Capacity"><br />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 2015-08-04
    • 2012-08-31
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多