我正在尝试做什么:
如何在页面上添加其他输入(使用jquery),然后在php中获取其内容?
答案 0 :(得分:5)
您无需显式地将输入添加到数组中。如果正确命名输入字段,PHP将自动将它们解析为数组。
<强> HTML 强>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jQuery dynamic input sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
// Input adding function
function addInput() {
$('#inputs').append('<p><input type="text" name="input[]"></p>');
}
// Event handler and the first input
$(document).ready(function () {
$('#adder').click(addInput);
addInput();
});
</script>
</head>
<body>
<form id="form" method="post" action="jquery.php">
<a id="adder" href="#">Add Input</a>
<div id="inputs">
</div>
<input type="submit" />
</form>
</body>
</html>
<强> PHP 强>
foreach ($_POST['input'] as $key => $value) {
echo "$key $value";
}
答案 1 :(得分:3)
也许这会奏效(如果我理解正确的话)
$('#add').click(function(){
$(this).before('<input name="array[]"/>');
});
和我的PHP
<?php
if (isset($_GET['array'])) {
for ($i=0; $i<count($_GET['array']); $i++) {
echo "array[$i] -> {$_GET['array'][$i]}";
}
}
?>
答案 2 :(得分:1)
我发布了一个类似的问题,虽然这个问题只涉及一个被克隆的输入,而不是多个输入。所以基本上,HTML就像是:
<form id="my_form">
<input name="my_input[1]" id="my_input[1]">
</form>
<a href="#" id="add_input">Add one more</a>
它的jQuery看起来像这样:
$("#add_input").click(function(event) {
// Get the number of current inputs and set the new count ...
var inputCount = parseInt($("input[id^=my_input]").size());
var newInputCount = inputCount++;
// ... then create new clone based on the first input ...
var newInput = $("#my_input[1]").clone();
// .. and do the cleanup, make sure it has
// an unique ID and name for server-side parsing
newInput.attr('id', 'my_input[' + newInputCount + ']').attr('name', 'my_input[' + newInputCount + ']').val('');
// .. and finally insert it after the last fieldset
newInput.insertAfter("#my_input[" + inputCount + "]");
event.preventDefault();
});
然后,在PHP方面,$_POST['my_input']
将是所有添加的字段值的数组,例如,使用foreach()
很容易迭代它们。
希望这有帮助!