简体   繁体   中英

Ajax multidimensional form data in same format as $_POST

I have a form with deep multidimensional inputs like so:

<form id="theForm">
 <input type='text' name='one[two][three][]' />
 <input type='text' name='one[two][three][]' />
 <input type='text' name='four[five][six][seven]' />
 <input type='text' name='eight[nine][ten]' />
</form>

I am trying to send the values via AJAX in the same format as if the form was submitted normally. What I mean is, if I were to hit the submit button, in PHP, $_POST would look like this. This is what I want:

array( 'one' => array( 'two' => array('three'=>array( [0] => "", [1] => "" ) ) ),
       'four' => array( 'five' => array ('six' => array( 'seven' => "" ) ) ),
       'eight' => array( 'nine' => array( 'ten' => "" ) ) )
     )

I am essentially trying to AJAX the form submission. When I do

$("#theForm").serializeArray()

And the send that over $.post() my $_POST looks like this:

array( [0] => array( "name" => string "one[two][three][]",  value=>"")
       [1] => array( "name" => string "one[two][three][]",  value=>"")
       [2] => array( "name" => string "four[five][six][seven]",  value=>"")
       [3] => array( "name" => string "eight[nine][ten]",  value=>"")
     )

This is of no use to me. I need to preserve the multidimensional structure I outlined before. I suppose I could walk through the array and chop up the string to recreate what I need, but this seems asinine to me. Is the a jQuery friendly way to accomplish this?

I've read the other posts about how jQuery can send multidimensional arrays just fine, so maybe the question I need to ask is, how do I extract my form data, keeping it in a multidimensional array?

My guess is when you are making the AJAX call you are doing:

data: {data: $("#theForm").serializeArray()}

Don't do that, just set data to the value of serializeArray .

data: $("#theForm").serializeArray()

EDIT : You said you are using $.post , and I assume you are doing this:

$.post('/your/url', {data: $("#theForm").serializeArray()}, function(){});

In order for it to work, you need to do it this way:

$.post('/your/url', $("#theForm").serializeArray(), function(){});

Accepted answer is totally correct. As a side note, if you need to add other data to the array of post data, you just need to push it onto the array in the format {name: "", value: ""}

In my case, I wanted to add a value based on a button that the user clicked, in addition to the values from all of the inputs in the form. So all you have to do is:

var data = $("#myForm").serializeArray();
data.push({name: "btnVal", value="button_a"});

And make sure you post like:

$.post("/some/url", data, function(){});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM