首先是代码:
<script type="text/javascript">
(function($){
$countForms = 1;
$.fn.addForms = function(idform){
var myform = "<table>"+
" <tr>"+
" <td>Field A ("+$countForms+"):</td>"+
" <td><input type='text' name='field["+$countForms+"][a]'></td>"+
" <td>Field B ("+$countForms+"):</td>"+
" <td><textarea name='field["+$countForms+"][b]'></textarea></td>"+
" <td><button>remove</button></td>"+
" </tr>"+
"</table>";
if(idform=='mybutton'){
myform = $("<div>"+myform+"</div>");
$("button", $(myform)).click(function(){ $(this).parent().parent().remove(); });
$(this).append(myform);
$countForms++;
}
};
})(jQuery);
$(function(){
$("#mybutton").bind("click", function(e){
e.preventDefault();
var idform=this.id;
if($countForms<3){
$("#container").addForms(idform);
}
});
});
<?php
$ligax=mysqli_connect('localhost','root');
if(!$ligax){
echo '<p> Falha na ligação.'; exit;
}
mysqli_select_db($ligax,'dados_arrays');
if ( isset( $_POST['field'] ) )
{
echo '<table>';
foreach ( $_POST['field'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['a'], '</td>';
echo ' <td>', $diam['b'], '</td>';
echo '</tr>';
}
echo '</table>';
}
?>
<body>
<div id="container"><div>
<form method="post" name="b" >
<table>
<tr>
<td>Field A</td>
<td><input type='text' name='field[0][a]'></td>
<td>Field B</td>
<td><textarea name="field[0][b]"></textarea></td>
<td><button>remove</button></td>
</tr>
</table>
</div>
</div>
<button id="mybutton">add form</button>
<div align="center">
<p><input type="submit" value="Registar" name="registar"></p>
</div>
<?php
if($ligax) mysqli_close($ligax);
?>
</body>
代码的第一部分是一个 jquery 函数,它在我需要时复制表单的字段。第二个是表单本身和用于接收来自表单的值的 $_POST 方法。
我的问题是这部分“foreach ($_POST['field'] as $diam)”没有从 jquery 的重复字段中捕获值。也许是因为它是在页面运行后出现的东西,我不知道。这就是为什么我需要帮助和建议。我如何捕获来自 jquery 生成的输入的值?
谢谢!