0

我想将多个角色传递给 servlet

 var params = {
       username : username,
       password : password       
 };
 var roles = [];  
 var role = $('#role').val();
 if(role.length > 1){
   for(var i = 0;i < role.length;i++){
      roles[i] =  role[i]
    }
 }
 else{
    params.role1 = role[0] ;
 }

如何执行此操作以使结果看起来像

 var params = {
       username : username,
       password : password,
       role1 : role1,
       role2 : role2,
       roleN : roleN,

  };
4

2 回答 2

2

您需要使用括号表示法,因为键是动态的

var params = {
    username: username,
    password: password
};
var roles = [];
var role = $('#role').val();
for (var i = 0; i < role.length; i++) {
    params['role' + (i + 1)] = role[i]
}
于 2013-10-15T10:08:10.013 回答
1

遍历角色集合并分配属性,如下所示:

role.forEach(function(r, i) {
    params['role'+(i+1)] = r;
});
于 2013-10-15T10:08:15.920 回答