我有1个php页面,包含2个表单和1个提交按钮。我想用这个单个按钮提交两个表单。我的代码工作正常,但有1个问题,在每个表单中只有1个字段提交成功。下面是我的html和javascript代码,请告诉我哪里有错误
2个html表格
<form name="form">
<input type="text" name="a" value="a">
<input type="text" name="b" value="b">
</form>
<form name="form">
<input type="text" name="c" value="c">
<input type="text" name="d" value="d">
</form>
<input type="submit" name="Submit" id="button" value="Submit" onClick="submitAllDocumentForms()">
Javascript代码
<script language="javascript" type="text/javascript">
/* Collect all forms in document to one and post it */
function submitAllDocumentForms() {
var arrDocForms = document.getElementsByTagName('form');
var formCollector = document.createElement("form");
with(formCollector)
{
method = "post";
action = "test.php";
name = "formCollector";
id = "formCollector";
}
for(var ix=0;ix<arrDocForms.length;ix++) {
appendFormVals2Form(arrDocForms[ix], formCollector);
}
document.body.appendChild(formCollector);
formCollector.submit();
}
/* Function: add all elements from ``frmCollectFrom´´ and append them to ``frmCollector´´ before returning ``frmCollector´´*/
function appendFormVals2Form(frmCollectFrom, frmCollector) {
var frm = frmCollectFrom.elements;
for(var ix = 0 ; ix < frm.length ; ix++)
frmCollector.appendChild(frm[ix]);
return frmCollector;
}
</script>
我的PHP代码来回显提交的值
<?php
echo $_POST['a'];
echo $_POST['b'];
echo $_POST['c'];
echo $_POST['d'];
?>
答案 0 :(得分:2)
问题是appendChild()
使元素远离表单,修改elements
数组及其长度。为避免这种情况,您可以例如存储变量中的元素数,并处理从最后一个元素开始的元素数组:
var frm = frmCollectFrom.elements;
var nElems = frm.length;
for(var ix = nElems - 1; ix >= 0 ; ix--)
frmCollector.appendChild(frm[ix]);