按表单字段jQuery ajax数据

时间:2011-09-27 02:07:37

标签: jquery ajax forms

我正在使用jQuery ajax处理表单 我有以下jQuery代码:

$.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>

它适用于ajax上的表单帖子。

在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 个答案:

答案 0 :(得分:1)

你是对的 - 在这种情况下使用.each()是正确的方法,但它只是让你迭代每个input元素,并且不会真正了解“数组” “在每个name属性中。这似乎是你的主要问题; javascript只是将name参数的值视为字符串,而不是值数组。

我不认为这是js眼中的多维数组...每个()只会看到一个大的元素列表,你需要发明自己的逻辑来解析。

这是我会尝试的......

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来电。

希望这有帮助