我正在尝试从已经动态创建的“用户名”ID中发布多个变量,例如“username1”,“username2”等。我正在寻找一种方法将这些变量动态发送到 ONE < / strong> ajax发布请求。我的问题主要是data
参数。
var numOfInputs = $('input').length;
$.ajax({
type: "POST",
url: "ajax.php",
// need way to dynamically pass more of these via numOfInputs.
data: ({username1 : $('#username1').val()}),
success: function(msg){
$('#statuses').html(msg);
}
});
请求html:
<input type="text" id="username1"></input><button id="add">+</button><button id="check">Check</button>
<div id="added-fields">
</div>
<div id="statuses">
</div>
答案 0 :(得分:2)
var data = {};
for (var i = 1; i <= numOfInputs; i++) {
data["username" + i] = $("#username" + i).val();
}
$.ajax(
...
data: data,
....
)
答案 1 :(得分:1)
你可以说:
$.ajax({
type: "POST",
url: "ajax.php",
data: $('input').map(function() {
var o = {};
o[this.id] = this.value;
return o;
});
...