2011-09-27 118 views
1

我正在處理與jQuery ajax形式。
我有以下的jQuery代碼:通過表單字段jQuery ajax數據

$.ajax({ 
    url: 'formprocess.php', 
    type: 'post', 
    data: $('#myForm input[type=\'text\']'), 
    dataType: 'json', 
    success: function(json) { alert('pass'); } 
}); 

我的形式是:

<form id="myForm"> 
    <input type="text" name="parent[47]child[230][26]" value="1" /> 
    <input type="text" name="parent[47]child[230][27]" value="2" /> 
    <input type="text" name="parent[28]child[231][29]" value="3" /> 
    <input type="text" name="parent[28]child[231][31]" value="4" /> 
</form> 

並能正常工作的表單發佈了阿賈克斯。

在PHP端它顯示爲:

$_POST 
: array = 
    parent: array = 
    47: array = 
     child: array = 
     230: array = 
      26: string = "1" 
      27: string = "2" 
    28: array = 
     child: array = 
     231: array = 
      29: string = "3" 
      31: string = "4" 

但我想,使其循環,並分別通過每個父母將其分割的JavaScript端。所以在這種情況下,它會回來後兩次:

$_POST 
: array = 
    parent_id = 47 
    child: array = 
     230: array = 
     26: string = "1" 
     27: string = "2" 

$_POST 
: array = 
    parent_id = 28 
    child: array = 
     231: array = 
     29: string = "3" 
     31: string = "4" 

所以我想我需要使用:

$('#myForm input[type=\'text\']').each(function(i, tbox) { 
    tboxname = tbox.attr('name'); 
    var myregexp = /parent\[(\d+)\]child\[(\d+)\]\[(\d+)\]/; 
    var match = myregexp.exec(tboxname); 
    var parent_id = match[1]; 
    var child = 'child['+match[2]+']['+match[3]+']'; 
} 

但現在我有2個字符串值和已經失去了我的目標和價值。

回答

1

你是正確的 - 在這種情況下,使用.each()是正確的做法,但它會只是讓你遍歷每個input元素,並不會真正瞭解了「數組」的name屬性爲每個裏面什麼一。這似乎是你的主要問題。 javascript只是將您的name參數的值看作一個字符串,而不是一組值。

我不會認爲這是js眼中的多維數組...... each()只會看到一個需要發明自己的邏輯來解析的元素列表。

這裏就是我會嘗試...

var parsedData = {}; 
$('#myForm input[type=\'text\']').each(function(i){ 
    var thisInput = $(this); 
    var thisName = $(this).attr('name'); 

    // parse your string here, by using conditional statements or maybe by using eval() 
    // ... This is where "your own logic" mentioned above would go =) 

    parsedData.["someValue"+i] = thisInput.val(); 
}); 

...,從這裏你可以使用parsedData VAR傳遞到您的通話$.ajax

希望這有助於

+0

這絕對讓我走了。我已經解析它並獲得我的parent_id變量。但是現在我怎樣才能讓其餘的數據以數組形式傳回。 – Dss

+0

嗯...也許你可以編輯你的原始問題?至於你的muli-dimensional'child'數組,你是否需要在每一個數組中實際傳遞整個數組,或者你只需​​要這些數字就可以返回到php?如果是前者,這將有助於瞭解陣列中需要的數據類型。如果是後者,你可以''Regex'(或'String.split()')來自'name'字符串的值,並將其作爲對象發佈到php?即。 '{'parent':123,'child':[230,26],'string':3}'? – Chazbot

+0

好吧,我重新編輯了我的問題 – Dss