Extjs 的checkbox复选框案例 动态获取数据(json)

本项目用struts2框架 ,Extjs3.4


1.
jsp文件中引用js,大部分Ext代码写在js文件中。
jsp文件:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>指派角色</title>
    <link rel="stylesheet" type="text/css" href="css/ext/ext-all.css" />
   	<script type="text/javascript" src="js/ext/ext-base.js"></script>
	<script type="text/javascript" src="js/ext/ext-all.js"></script>

    <script type="text/javascript" src="js/ext/form/states.js"></script>
    <script type="text/javascript" src="js/ext/form/assign_role.js"></script>
    <link rel="stylesheet" type="text/css" href="css/ext/forms.css"/>

    <!-- Common Styles for the examples -->
<script type="text/javascript" src="js/ext/examples.js"></script>
<link href="css/ext/ext-patch.css"  type="text/css" rel="stylesheet"/>
</head>
<body>
<div id="grid"></div>
<input type="hidden" name="userid" id="userid" value='<s:property value="userid"/>'/>
<input type="hidden" name="user.username" id="user.username" value='<s:property value="user.username"/>'/>
</body>
</html>







2.  assign_role.js文件:


/*!
 * Ext JS Library 3.4.0
 * Copyright(c) 2006-2011 Sencha Inc.
 * [email protected]
 * http://www.sencha.com/license
 */

Ext.onReady(function(){

  var userid;
  var json='';
 Ext.Ajax.request({ 
              url: 'role_checkboxJson.action',
              params: {userid:document.getElementById('userid').value},
              method: 'POST',
              dataType:'json',
              success: function(response,options){
             json=Ext.util.JSON.decode(response.responseText); 
        
         var checkGroup = new Ext.form.FieldSet({
        xtype: 'fieldset',
        title: '授权'+ (document.getElementById('user.username').value?'('+document.getElementById('user.username').value+')':''),
        autoHeight: true,
        layout: 'form',
    //    collapsed: true,   // initially collapse the group
        collapsible: true,
        items: [{
            id:'cc',
            xtype: 'checkboxgroup',
            fieldLabel: '选择角色 ',
            name:'FileItype',
            // Distribute controls across 3 even columns, filling each row
            // from left to right before starting the next row
            columns: 4,
            items:json
        }]

    });   
        	  
        
    var asignResource_form = new Ext.FormPanel({
    //    title: '指派资源',
        frame: true,
        labelWidth: 110,
        width: 600,
        renderTo:'grid',
    //    bodyStyle: 'padding:0 10px 0;',
        items: [
     checkGroup
        ],
        buttons: [{
            text: '授权',
            handler: function(){
          var FileItype=asignResource_form.getForm().findField('FileItype').getValue();
          var as=[];
          for(i=0;i<FileItype.length;i++)
            {
            as[i]=FileItype[i].inputValue;
            }
     //     alert(as);
             if(asignResource_form.form.isValid()){        
              //提交到服务器操作
                 asignResource_form.form.doAction('submit',{
                            url:'assignRole.action',//文件路径
                            method:'post',//提交方法post或get 
                            params:{userid:document.getElementById('userid').value},    
                            //提交成功的回调函数
                            success:function(form,action){
                                 if (action.result.success==true) {
                                  Ext.Msg.alert('指派成功',action.result.msg);
                                  //刷新父窗口、关闭本窗口
                                   var win2 = parent.Ext.getCmp('win');
                                   if (win2) {win2.close();}   
                                //  window.parent.location.href='userGrid.action';
                               //   window.close();
                                 // window.document.location='roleGrid.action';
                                 } else {
                                    Ext.Msg.alert('指派错误',action.result.msg);
                                 }
                            },
                            //提交失败的回调函数
                            failure:function(){                           
                                 Ext.Msg.alert('错误','服务器出现错误请稍后再试!');
                            }
                          });
           }
         //     alert(Ext.get('resources').dom.value );
            }}
        ,{
            text: '重置',
            handler: function(){
            asignResource_form.getForm().reset();
            }
        },{//因为我这个窗口,是放在了某个界面弹出的win窗口,
             //点击关闭可关闭弹出的窗口,在单独的页面是不执行的。
            text: '关闭',
            handler: function(){
                 var win2 = parent.Ext.getCmp('win');
            if (win2) {win2.close();}         
            }
        }]
    });
           
            }
          });  

    // turn on validation errors beside the field globally
    //显示验证错误的位置,改为旁边
    Ext.form.Field.prototype.msgTarget = 'side';

});




3. 'role_checkboxJson.action'连接对应的方法,传递了一个userid值,根据值判断复选框状态,若此用户已经选择了,则页面显示勾选,checked=true
手写生成json格式数据:

public String RoleCheckBoxJson(int userid) {
		if(userid==0){
			return null;
		}
		List<Role> roles = ((RoleMapper) mapper).getRolesByUserId(userid);
		List<Role> allroles= ((RoleMapper)mapper).getAllRoles();
		System.out.println(roles.size());
		for(int j=0;j<roles.size();j++){
			System.out.println(roles.get(j).getId());
		}
		if(roles==null){
			return null;
		}  //[{boxLabel: 'Item 2', name: 'resource_id', inputValue : 2,checked: true},{}]
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (int i = 0; i < allroles.size(); i++) {
			boolean flag=false;
			Role r = allroles.get(i);
			sb.append("{");
			sb.append("id:\'").append(i).append("\',");
			sb.append("boxLabel:\'").append(r.getNote()).append("\',");
			sb.append("name:\'").append("role_id").append("\',");
			sb.append("inputValue:\'").append(r.getId()).append("\',");
			for(int j=0;j<roles.size();j++){
				System.out.println(roles.get(j).getId());
				System.out.println(allroles.get(i).getId());
			  if(roles.get(j).getId()==allroles.get(i).getId()){
				  flag=true;
			  }				
			}
		   if(flag==true){
			   sb.append("checked:").append(true); 
		   }else{
			   sb.append("checked:").append(false); 
		   }
			sb.append("}");
			if (i < allroles.size() - 1) {
				sb.append(',');
			}
		}
		sb.append("]");
		return sb.toString();
	}


4.Json所得到的数据为:
[{id:'0',boxLabel:'XX管理员',name:'role_id',inputValue:'1',checked:true},{id:'1',boxLabel:'XX管理员',name:'role_id',inputValue:'3',checked:true},{id:'2',boxLabel:'XX管理员',name:'role_id',inputValue:'10',checked:false},{id:'3',boxLabel:'用户',name:'role_id',inputValue:'11',checked:false}]

其中,boxLabel为复选框对应文字,name为提交的参数名,inputValue为选项值。

你可能感兴趣的:(JavaScript,Ajax,json,ext,checkbox)