I am processing a form with jQuery ajax.
I have the following jQuery code:$.ajax({
url: 'formprocess.php',
type: 'post',
data: $('#myForm input[type=\'text\']'),
dataType: 'json',
success: function(json) { alert('pass'); }
});
And my form is:
<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>
And it works fine for form posts over ajax.
On the php side it shows up as:
$_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"
But I'd like to split it on the javascript side so that it loops and passes each parent separately. So in this case it would post back twice:
$_POST
: array =
parent_id = 47
child: array =
230: array =
26: string = "1"
27: string = "2"
AND
$_POST
: array =
parent_id = 28
child: array =
231: array =
29: string = "3"
31: string = "4"
So I think I need to use:
$('#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]+']';
}
But now I have 2 string values and have lost my object and value.
You're correct - using .each()
in this case is the right approach, but it'll just let you iterate over each input
element, and won't really know anything about the "array" inside the name
attribute for each one. That seems to be your primary issue here; javascript is just seeing the value of your name
parameter as a string, and not an array of values.
I wouldn't think of this as a multi-dimensional array in the eyes of js... the each() will just see one big list of elements that you need to invent your own logic to parse through.
Here's what I would try...
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();
});
...And from here you would use the parsedData
var to pass into your $.ajax
call.
Hope this helps
精彩评论