通过ajax将多维动态表单传递给PHP

时间:2015-09-24 12:39:10

标签: javascript php ajax

我正在为我们的平台开发一个邀请系统。最终用户将能够根据需要添加尽可能多的用户。为此,我准备了一个动态表格:

HTML:

                <div class="col-xs-3">
                    <input type="text" class="form-control" id="user0first_name" name="user[0]first_name" placeholder="First Name" />
                </div>
                <div class="col-xs-3">
                    <input type="text" class="form-control" id="user0last_name" name="user[0]last_name" placeholder="Last Name" />
                </div>
                <div class="col-xs-4">
                    <input type="text" class="form-control" id="user0email" name="user[0]email" placeholder="Email" />
                </div>

JS

$("#invitation").click(function(event){
    var data = {};

    for (var i = 0; i <= emailIndex; i++) {
       data["user[" + i + "]first_name"] = $("#user" + i + "first_name").val();
       data["user[" + i + "]last_name"] = $("#user" + i + "last_name").val();
       data["user[" + i + "]email"] = $("#user" + i + "email").val();
    }

    console.log(data);

PHP

    $name = $_POST['user'];

    foreach( $name as $v ) {
        print $v['first_name'];
    }

这只是打印“电子邮件”栏目:

Email1valueEmail2value

我也需要抓住名字和姓氏。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

使用Javascript:

$("#invitation").click(function(event){
var data = [];
for (var i = 0; i <= emailIndex; i++) {
   var obj = new Object();
   obj.first_name = $("#user" + i + "first_name").val();
   obj.last_name = $("#user" + i + "last_name").val();
   obj.email = $("#user" + i + "email").val();
   data.push(obj);
}
console.log(data);

PHP

$name = $_POST['user'];
foreach( $name as $v ) {
    print $v['first_name'];
}