2013-04-20 53 views
0

我有多個輸入字段這樣的:獲取jQuery中輸入數組的值,並將其傳遞給PHP

<input type="text" name="childage[3]" placeholder="0"/> 
<input type="text" name="childage[8]" placeholder="0"/> 
<input type="text" name="childage[12]" placeholder="0"/> 

我想他們到jQuery和與AJAX它們傳遞到PHP但要記住的鑰匙(3 ,8,12)。這可能嗎?

我想直到現在以下幾點:

$('input[name="childage[]"]'); 
$('input[name="childage"'); 

回答

3

你應該看看serialize方法:

http://docs.jquery.com/Ajax/serialize

你會想抓住所有的表單元素,像這個:

<input class="age-box" type="text" name="childage[3]" placeholder="0"/> 
<input class="age-box" type="text" name="childage[8]" placeholder="0"/> 
<input class="age-box" type="text" name="childage[12]" placeholder="0"/> 

var ages = $('.age-box').serialize(); 
$.post(url, ages, function(data) { //handle response from the server }); 
+0

請注意,serialize將替換用於url編碼的'['和']'。你將不得不將它們替換回'$('。age-box')。serialize()。replace(/%5B/g,'[').replace(/%5D/g,']');'或與類似的東西。 – Spokey 2013-04-20 20:07:09

+0

謝謝!在PHP中,我使用了parse_str($ _ POST ['fields'],$ fields);它的工作原理 – 2013-04-20 20:08:37

0

你可以使用隱藏輸入字段並將值設置爲您需要的數字:

<input type="hidden" value=3 /> 
<input type="hidden" value=8 /> 
<input type="hidden" value=12 /> 

// Get the values 
$('input[type="hidden"]')[0].val(); 
$('input[type="hidden"]')[1].val(); 
$('input[type="hidden"]')[2].val(); 
相關問題