2012-03-03 242 views
2

我有1個PHP頁面包含2個表單和1個提交button.i想要提交這兩個表單與這個單一的button.My代碼完美的作品,但有1個問題,在每個表單只1字段已成功提交。下面是我的HTML和JavaScript代碼,PLZ告訴我哪裏有錯誤在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']; 
?> 

回答

2

問題是appendChild()將元素從表單中移走,修改了elements數組以及它的長度。爲了避免這種情況,你可以將元素的數量存儲在一個變量中,並處理從最後一個元素開始的元素數組:

var frm = frmCollectFrom.elements; 
var nElems = frm.length; 
for(var ix = nElems - 1; ix >= 0 ; ix--) 
    frmCollector.appendChild(frm[ix]); 
+0

waaaaw太棒了,它的工作完美,謝謝100萬 – Arif 2012-03-04 05:14:07