2010-08-20 83 views
2

我一直在開發一個動態生成的表單,該表單將類似於下面示例的多個項目傳遞給PHP腳本。如何使用PHP腳本處理ajax表單參數

<div class="menu-item"> 
<input type="text" value="3" readonly="readonly" class="quantity" name="quantity"> 
<input type="text" value="Menu Item 3" readonly="readonly" class="item" name="item"> 
<input type="text" value="80.00" readonly="readonly" class="price" name="price"> 
</div> 
...etc 

我的問題是,因爲我不會放棄爲quantityitemprice一個唯一的標識符,我得到這些通過傳遞給服務器端的參數name屬性:

quantity=3&item=Menu+Item+3&price=80.00&quantity=2&item=Menu+Item+2&price=50.00&quantity=1&item=Menu+Item+1&price=30.00&total=370.00&name=Alex&table=10&terms=on 

我可以很容易地改變它,所以name會是quantity1,item1,price1,quantity2,item2,price2等,但無論如何我不知道如何最好的使用PHP循環這些參數集,所以我可以確保我處理每個quantityitemprice對應的項目。

謝謝, 亞歷克斯

+0

哪裏jQuery的來到這個? – Ender 2010-08-20 23:26:52

+0

我正在設置場景,它用於將帖子數據傳遞給PHP腳本 – Alex 2010-08-20 23:30:39

+0

可能的重複:http://stackoverflow.com/questions/3314567/how-to-get-form-input-array-into-php- array – 2010-08-20 23:36:35

回答

6

如果你的名字一樣quantity[]item[]price[]領域,PHP將它們組裝成每樣東西的名字命名的數組。只要確保頁面上的所有數量,商品和價格都是相同的順序(並且它們都不會跳過一個字段),並且$_POST['quantity'][0]將是第一個數量,$_POST['price'][0]第一個價格等。

+0

+1 ...你很快:-) – a1ex07 2010-08-20 23:34:44

+0

我很無聊。什麼都不做,但通過SO尋找問題來回答並獲得回報。 :) – cHao 2010-08-20 23:35:25

+0

謝謝你,很好的解決方案 – Alex 2010-08-20 23:52:03

0

什麼我通常的做法如下:

使用以下名稱生成表單:quantity-x,item-x,price-x;

這是你如何處理它:

$values = array(); 
foreach($_POST AS $key => $value){ 
$keyPart = explode('-',$key); 
$values[$keyPart[1]][$keyPart[0]] = $value 
} 

這將產生其中每個元素都包含與分組值的數組的數組。所以元素0將是[quantity-1,price-1,item-1]和1將是[quantity-2,price-2,item-2]

這種方式的價值是你沒有跟蹤您的元素的順序。由於唯一標識符可以直接鏈接到數據庫主鍵。缺點是,你將不得不重複兩次。

編輯:這也將在$ _GET

0

假設你只有那些通過GET進來的變量的工作,這將是一個辦法:

//number of fields/item 
$fields = 3; 
$itemCount = count($_GET)/$fields; 

for ($i = 1; i <= $fields; i++) { 
    $quantity = $_GET['quantity'.i]; 
    $item = $_GET['item'.i]; 
    $price = $_GET['price'.i]; 
    processFields($quantity, $item, $price); 
}