easyui datagrid 动态生成列的实现
- function sqlSearch(){
- var sqlStatement = $.trim($("#sqlStatementId").val());
- if(sqlStatement == null || sqlStatement == ""){
- return false;
- }
- var type = "POST";
- var url = "sqlExecCtrl.action?cmd=getColumnNameList";
- var param = "sqlStatement=" + $("#sqlStatementId").val();
- ajaxExtend(type,url,param,function(data){
- var options = $("#sqlResultDisplay").datagrid("options"); //取出当前datagrid的配置
- options.columns = eval(data.columns); //添加服务器端返回的columns配置信息
- options.queryParams = getQueryParams("sqlConditionId"); //添加查询参数
- $("#sqlResultDisplay").datagrid(options) ;
- $("#sqlResultDisplay").datagrid("load") ; //获取当前页信息
- });
- }
- /**
- * 根据指定条件请求系统资源
- *1、 异步
- *2、返回格式为json
- *
- * @param type //请求方式
- * @param url //请求url
- * @param param //请求参数
- * @param callback //回调函数
- */
- function ajaxExtend(type,url,param,callback){
- ajaxExtendBase(type,url,param,true,callback);
- }
- /**
- * ajax请求基础方法
- * @param type
- * @param url
- * @param param
- * @param async
- * @param callback
- */
- function ajaxExtendBase(type,url,param,async,callback){
- $.ajax({
- type: type,
- url: url,
- data:param,
- async : async,
- dataType:"json",
- success:function(result){
- if(result.success){ //只有sql正确能获取相关列名后才再请求列表资源
- callback(result.data); //获取当前页信息
- }
- else{
- dealWithException(result.exception);
- }
- }
- });
- }
- /**
- * 将指定form参数转换为json对象
- */
- function getQueryParams(conditionFormId){
- var searchCondition = getJqueryObjById(conditionFormId).serialize();
- var obj = {};
- var pairs = searchCondition.split('&');
- var name,value;
- $.each(pairs, function(i,pair) {
- pair = pair.split('=');
- name = decodeURIComponent(pair[0]);
- value = decodeURIComponent(pair[1]);
- obj[name] = !obj[name] ? value :[].concat(obj[name]).concat(value); //若有多个同名称的参数,则拼接
- });
- return obj;
- }
后台返回的json格式如下
- {"total":3,
- "columns":[[{"field":"ROLE_ID","title":"ROLE_ID","width":100,"resizable":true},
- {"field":"NAME","title":"NAME","width":100,"resizable":true},
- {"field":"CREATE_DATE","title":"CREATE_DATE","width":100,"resizable":true},
- {"field":"DESCRIPTION","title":"DESCRIPTION","width":100,"resizable":true}]],
- "rows":[{"NAME":"普通人员","DESCRIPTION":"只具有查看权限","CREATE_DATE":"2012-09-21 16:31:53.0","ROLE_ID":"7"},
- {"NAME":"调度人员","DESCRIPTION":"开放全部功能,但无系统管理相关权限","CREATE_DATE":"2012-09-21 16:32:24.0","ROLE_ID":"8"},
- {"NAME":"超级管理员","DESCRIPTION":"具有所有权限","CREATE_DATE":"2012-09-17 20:23:19.0","ROLE_ID":"1"}]}
其中,"columns"对应sqlSearch方法的ajaxExtend(type,url,param,function(data){})回调函数中的data,"total"和"rows"为datagrid加载数据
效果图: