jQuery jquery输入数组表单ajax
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7856980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery input array form ajax
提问by user892134
How do i get the input array username
values in the jQuery variable users
?
如何获取username
jQuery 变量中的输入数组值users
?
<input type='text' name='username[]' class='users' value='test1' />
<input type='text' name='username[]' class='users' value='test2' />
<input type='text' name='username[]' class='users' value='test3' />
<div class='submit'>Submit</div>
<script type="text/javascript">
$(function() {
$('.submit').click(function() {
var users =
var dataString = 'users=' + users;
$.ajax({
type:'POST',
url:'users.php',
data: dataString,
success: function() {
}
});
});
});
</script>
回答by C???
Check out jQuery.serialize()
. It should give you an array of the usernames.
退房jQuery.serialize()
。它应该给你一个用户名数组。
var users = $('input:text.users').serialize();
You can be however lazy or specific with the selector: .users
,input.users
,form .users
would all work, plus a few more.
但是,您可以使用选择器变得懒惰或特定:.users
, input.users
,form .users
都可以,再加上一些。
For this example:
对于这个例子:
// users =
username[]=test1&username[]=test2&username[]=test3
Which, depending on your server-side technology, will come through in the request as an array of strings for the key "username" (PHP, for example).
根据您的服务器端技术,哪个将作为键“用户名”(例如 PHP)的字符串数组出现在请求中。
回答by Nechehin
<script>
$(function() {
$('.submit').click(function() {
// Get data as array, ['Jon', 'Mike']
var users = $('input[name="username[]"]').map(function(){
return this.value;
}).get();
$.ajax({
type: 'POST',
url: 'users.php',
data: {
'username[]': users,
// other data
},
success: function() {
}
});
});
});
</script>
回答by mu is too short
You can use map
to get an array:
您可以使用map
获取数组:
// from inside the submit callback
var users = $(this).find('.users').map(function(i, el) {
return el.value;
});
Demo (run with the console open): http://jsfiddle.net/ambiguous/w2RRW/
演示(打开控制台运行):http: //jsfiddle.net/ambiguous/w2RRW/