post checkbox data using jquery
i have some html snip like this
<input type="checkbox" name="color" value="red"/>red
<input type="checkbox" name="color" value="green"/>green
<input type="checkbox" name="color" value="purple"/>purple
<input type="checkbox" name="color" value="grey"/>grey
and i want to use jquery to post value t开发者_JS百科o server, so i used jquery like this
$.post('/test', {'color': ['red', 'green']});
i did search this question in stackoverflow, but people say it's should be 'color[]' instead of 'color', but whenever i used 'color' or 'color[]' firebug displayed the post data is 'color%5B%5D=red&color%5B%5D=green', and my server can't work right, but when using
<input type="submit" value="submit"/>
to post firebug says the data is 'color=red&color=green', and my server work right. How could it be? my jquery version is 1.4.4
I believe that when you call -
$.post('/test', {'color': ['red', 'green']});
an array is being passed as the post data and the flattening of the array is what's causing the 'color%5B%5D=red&color%5B%5D=green' result.
If you use the following -
$('input:checkbox[name="color"][checked=true]').serialize()
This should return all of the checked checkboxes in the 'color=red&color=green' format. There's a jsfiddle that attempts to illustrate the concept here - http://jsfiddle.net/789nP/.
For some reason, the jQuery developers decided that PHP's bizarre handling of multiple controls with the same name is The Correct Way. As a consequence, when submitting an array of data, jQuery will append []
to the name (%5B%5D
is just a URL encoded representation of []
).
to post firebug says the data is 'color=red&color=green', and my server work right
That suggests that you are using something other than PHP to process the data so PHP's magic handling of []
in names does not apply.
You can either look for color[]
on the server…
e.g.
@values = $query->param('color[]');
… or you can set traditional mode to stop jQuery PHPifying your data.
$.post('/test', {'color': ['red', 'green']}, { traditional: true });
Then normal access should work:
@values = $query->param('color');
精彩评论