how to send multi field value by jquery post
I know how to send by jquery post method $.post("test.php", { name: "John", time: "2pm" } );
but what if my form field name is array
<input type=text name="n1[]" id="n1[]" value='12345">
<input type=text name="n1[]" i开发者_运维知识库d="n1[]" value="14454">
how to send these 2 field value send to url by jquery post method?
You can pass in an array as a value in the object:
{name: 'John', 'nl[]': ['12345', '14454']}
(This is documented at ajax but also works for post.)
However probably better if you can is to use the serialize method of the form to create the data string, then you can let jQuery worry about getting it right. jQuery (and HTML in general) doesn't care about whether there are square brackets at the end of a field control name. That's only a hack used to tell PHP that it should expect multiple values.
Note nl[]
is an invalid ID. Apart from validation/compatibility problems, it will also make it hard for you to write selectors to get, as the square brackets in $('#nl[]')
mean something else. You can backslash-escape them in this case, though there are some places where jQuery's regex-hack selector parsing breaks stuff like this.
Plus, you can't have two elements with the same id
on the page. id
has the job of identifying a single element on the page with a simple alphanumeric* name for scripting and stylesheet purposes; it is not a replacement or alternative to the name
attribute of form fields, which is the control name to send to the server.
(*: plus .-_:
though you don't generally want to use :
, and .
also makes writing selectors annoying.)
[Finally a simple typo: your first value
is also misquoted.]
var fields = $(":input").serializeArray();
$.post("test.php",fields);
See documentation on serializeArray( ) and the input selector.
精彩评论