jTable插件辅助资料

2018-11-05 15:55:00 浏览数 (1)

版权声明:本文为博主原创文章,未经博主允许不得转载。

==============================================jTable插件================================================ 【】引入jtable <link rel="stylesheet" type="text/css" href="../jtable/themes/lightcolor/blue/jtable.min.css" /> <script type="text/javascript" src="../jtable/jquery.jtable.min.js"></script> <script type="text/javascript" src="../jtable/localization/jquery.jtable.zh-CN.js"></script> 注:jTable插件需要jquery UI插件。之前要引入jQuery和jQueryUI 【】Servlet生成JSON结果 collegeList=collegeBusiness.getListByAll(); //定义数据返回JSON map Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put("Result", "OK"); jsonMap.put("Records", collegeList); JSONObject result=JSONObject.fromObject(jsonMap); HttpServletResponse response=ServletActionContext.getResponse(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out=response.getWriter(); out.println(result.toString()); out.flush(); out.close(); 【】jtable要求的返回格式 {  "Result":"OK",  "Records":[   {"PersonId":1,"Name":"Benjamin Button","Age":17,"RecordDate":"/Date(1320259705710)/"},   {"PersonId":2,"Name":"Douglas Adams","Age":42,"RecordDate":"/Date(1320259705710)/"},   {"PersonId":3,"Name":"Isaac Asimov","Age":26,"RecordDate":"/Date(1320259705710)/"},   {"PersonId":4,"Name":"Thomas More","Age":65,"RecordDate":"/Date(1320259705710)/"}  ] } 【】当出现异常后的jTable要求的结果 {    "Result":"ERROR",    "Message":"异常信息字符串" } 【】jTable的语法  $('#MyTableContainer').jtable({             //General options comes here             actions: {                 //Action definitions comes here             },             fields: {                 //Field definitions comes here             }             //Event handlers... });      【】jtable初始化 1.定义jTable显示的区域div <div id="departmentmaincontent"> </div> 2.在JS中初始化jTable //定义部门表格 $('div#departmentmaincontent').jtable({            title: '部门列表',            selecting: true, //Enable selecting            multiselect: false, //not Allow multiple selecting            actions: {                listAction: '../department/list.do'            },            fields: {                no: { title: '部门编号',                    width: '20%'                },                code: { title: '部门编码',                       width: '20%'                   },                name: {                    title: '部门名称',                    width: '60%'                }            },            selectionChanged: function () { var selectedRows= $('div#departmentmaincontent').jtable('selectedRows');  selectedRows.each(function () { var record=$(this).data('record'); departmentNo=record.cno; });            }      }); 3.执行AJAX查询载入数据 //载入部门列表 $('div#departmentmaincontent').jtable('load'); 无数据发送的情况 $('div#departmentmaincontent').jtable('load',{name:value,name:value}); 有数据提交的情况 4.取得选中的行的字段信息: var $selectedRows = $('#PersonTable').jtable('selectedRows'); $selectedRows.each(function () {     var record = $(this).data('record');     var personId = record.PersonId;     var name = record.Name; }); 【】jTable分页传递的参数 //起始记录 private int jtStartIndex=0; //页面的显示行数 private int jtPageSize=0; 【】Strust2符合jTable要求的JSON结果配置  <action name="tolist01" class="behaveMainAction" method="tolist01">    <result name="tolist01" type="json"> <param name="contentType">text/html;charset=UTF-8</param> <param name="root">listResult</param> <param name="excludeProperties">behaveBusiness,behaveList,bv, behaveNo</param> <param name="includeProperties">Result,Records[d ].name,Records[d ].no</param> </result> </action> 【】jTable的option选项 1. 2. 3. 4. 5. 6. 设置jtable的工具栏 toolbar: {     items: [{         icon: '/images/excel.png',         text: 'Export to Excel',         click: function () {             //perform your custom job...         }     },{         icon: '/images/pdf.png',         text: 'Export to Pdf',         click: function () {             //perform your custom job...         }     }] }, 7. 【】设置jTable的选项 1 $('#MyTableContainer').jtable('option', 'pageSize', 20); 2. $('#MyTableContainer').jtable({     "name":value,     "name":value }); 3. 【】jtable的action 1.listaction 用于指定列表的取得 actions: {                listAction: '../department/tolist.action'            } 2.返回结果的格式: {         "Result": "OK",         "Records": [             { "StudentId": 39, "ContinentalId": 1, "CountryId": 18, "CityId": 55, "Name": "Agatha Garcia", "EmailAddress": "agatha.garcia@jtable.org", "Password": "123", "Gender": "F", "BirthDate": "/Date(-1125111600000)/", "About": "", "Education": 2, "IsActive": true, "RecordDate": "/Date(1369083600000)/" },             { "StudentId": 61, "ContinentalId": 4, "CountryId": 1, "CityId": 1, "Name": "Agatha Lafore", "EmailAddress": "agatha.lafore@jtable.org", "Password": "123", "Gender": "F", "BirthDate": "/Date(1017694800000)/", "About": "", "Education": 3, "IsActive": true, "RecordDate": "/Date(1393192800000)/" }],         "TotalRecordCount": 2  } 3.与分页相关的属性:  paging: true, //Enable paging 启用jTable的分页  pageSize: 10, If paging is enabled, jTable sends two query string parameters to the server on listAction AJAX call: jtStartIndex:  Start index of records for current page. jtPageSize:  Count of maximum expected records. TotalRecordCount:  Total count of records (not only this page 【】jTable的方法 1.load(postData, completeCallback) 载入方法:重新载入listAction指定的服务器URL地址: $('#PersonTable').jtable('load', { CityId: 2, Name: 'Halil' }); 2.selectedRows() 取得选择的所有行 案例:取得选择行的属性值。 var $selectedRows = $('#PersonTable').jtable('selectedRows'); $selectedRows.each(function () {     var record = $(this).data('record');     var personId = record.PersonId;     var name = record.Name; }); 【】 jTable显示关联对象的属性  $('div#lessonTimemaincontent').jtable({            title: '课次列表',            selecting: true, //Enable selecting            multiselect: false, //not Allow multiple selecting            actions: {                listAction: '../lessonTime/tolist.action?lessonNo=' lessonNo            },            fields: {                xno: { title: '课次编号',                    width: '10%'                },                xnum: {                    title: '课次数',                    width: '10%'                },                rv: {                    title: '教室',                    width: '20%',                    display:function(data){ if(data.record.rv) return data.record.rv.jname; else return ;                    }                },                first: {                    title: '开始时间',                    width: '20%'                },                last: {                    title: '结束时间',                    width: '20%'                }            },            selectionChanged: function () { var selectedRows= $('div#lessonTimemaincontent').jtable('selectedRows');  selectedRows.each(function () { var record=$(this).data('record'); lessonTimeNo=record.xno; });            }      }); 【】 ..... gender: {          title: 'Gender',          key: true }, homeNo: {         title: 'Home-No',         key: true,         display:function(data){                    return data.record.address.homeNo;         } }, street: {         title: 'Street',         key: true,         display:function(data){                    return data.record.address.street;            } }, city: {       title: 'City',       key: true,       display:function(data){                 return data.record.address.city;       } }, province: {            title: 'Province',            key: true,            display:function(data){                      return data.record.address.province;            } }, firstName: {         title: 'First Name',         display:function(data){                    return data.record.name.firstName;         } }, middleName: {         title: 'Middle Name',         display:function(data){                   return data.record.name.middleName;         } }, lastName: {         title: 'Last Name',         display:function(data){                   return data.record.name.lastName;         } }, ........ 【】  fields: {              visitType1 : {                     title : 'Visit Type',                     width : '30%',                     key : true,                     list : true,                     edit : false,                     create : true                 },                 visitorId : {                         title : 'Visitor Id',                         width : '30%',                           edit : false,                         create : false,                          display:function(data){                                return data.record.visitor.visitorId;                        }                     }           } 【】field属性定义: jTable API Reference - Field options columnResizable create edit defaultValue dependsOn display input inputClass inputTitle key list listClass options optionsSorting sorting title type visibility width A field definition defines structure and behavior of a field of the record. It's generally formatted as: ? 1 2 3 FieldName: {     //Field options } columnResizable boolean default: true A boolean value that indicates whether this column can be resized by user. Table's columnResizable option must be set to true (it's default) to use this option. create boolean default: true A boolean value that indicates whether this field is shown in the create record form. Default value is false for the key field. True for other fields. edit boolean default: true A boolean value that indicates whether this field is shown in the edit record form. Default value is false for the key field. True for other fields. defaultValue string default: none You can set a default value for a field. It must be a valid value. For instance, if the field is an option list, it must be one of these options. dependsOn string or array default: none This option is used to create cascaded dropdowns. If a combobox field depends on another combobox, jTable can automatically create cascaded dropdowns. See demo for usage. Here, there is a sample usage of this option to provide Country/City cascade comboboxes: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 CountryId: {     title: 'Country',     options: 'Demo/GetCountryOptions',     list: false }, CityId: {     title: 'City',     dependsOn: 'CountryId', //Cities depends on countries.     options: function (data) {         if (data.source == 'list') {             //Return url of all cities for optimization.              return 'Demo/GetCityOptions?countryId=0';         }         //This code runs when user opens edit/create form or changes country combobox on an edit/create form.         return 'Demo/GetCityOptions?countryId=' data.dependedValues.CountryId;     } } A field can be depended to more than one field. In this case, you can write fields seperated by comma as dependsOn: 'ContinentalId,CountryId' or as an array like dependsOn: ['ContinentalId', 'CountryId'] See options option for more information. display function default: none This option is a function that allows you to define a fully custom column for table. jTable directly shows return value of this function on the table. See the sample below: ? 1 2 3 4 5 6 TestColumn: {     title: 'Test',     display: function (data) {         return '<b>test</b>';     } } This sample Test column returns a bold 'test' string for all rows. You can return any text, html code or jQuery object that will be shown on the table. This method is called for each row. You can get record of the row using data.record. So, if your record has Name property, you can use data.record.Name property to get the Name. display function can be used for many purposes such as creating calculated columns, opening child tables for a row... etc. See demos for detailed usage. input function default: none This option is a function that allows you to define a fully custom input element for create and edit forms. jTable directly shows return value of this function on the form. See the sample below: ? 1 2 3 4 5 6 7 8 9 10 11 Name: {     title: 'Name',     width: '20%',     input: function (data) {         if (data.record) {             return '<input type="text" name="Name" style="width:200px" value="' data.record.Name '" />';         } else {             return '<input type="text" name="Name" style="width:200px" value="enter your name here" />';         }     } } data argument has some fields those can be used while creating the input: data.formType: Can be 'create' or 'edit' according to the form. data.form: Reference to the form element as jQuery selection. data.record: Gets the editing record if this input is being created for edit form (if formType='edit'). So, it's undefined for 'create' form. data.value: Gets current value of the field. This is default value (if defined) of field for create form, current value of field for edit form. While jTable automatically creates appropriate input element for each field, you can use input option to create custom input elements. Remember to set name attribute of input element if you want to post this field to the server. inputClass string default: none A string value that can be set as the class of an input item for this field in create/edit forms. So you can style input elements in the forms for this field. This can be useful when working with validation plug-ins (we will see soon). inputTitle string default: none This option can be used to show a different title for a field in edit/create forms. If it's not set, input title will be same as title option. key boolean default: false A boolean value that indicates whether this field is the key (primary key) field of the record. Every record must has one and only one key field that is used on update and delete operations. If a field is marked as key, create and edit options are set to false as default. If a key field is not editable in edit form, a hidden input element is generated for it. Thus, key value is post to server. If the key field is editable (with setting edit option to true), key's original value (the value before update) is post to server as jtRecordKey. list boolean default: true A boolean value that indicates whether this field is shown in the table. listClass string default: none A string value that can be set as class/classes of a cell of this field (td element) in the table. Thus, you can stylize fields in the table. options object, array, URL or a function default: none If this field's value will be selected in an option list (combobox as default, can be radio button list), you must supply a source. An option source can be one of these values: object: Property names are values, property values are display texts. array: An array of options. URL: A URL to download the option list for this field. function: A function that takes some arguments and returns an object, an array or a URL string. Defining an object This is the simplest way of defining options is creating an object like shown below: ? 1 2 3 4 PhoneType: {     title: 'Phone type',     options: { '1': 'Home phone', '2': 'Office phone', '3': 'Cell phone' } } Thus, jTable creates a dropdown list in edit/create form for that field: '1', '2' and '3' are values of combobox items respectively. Defining an array You can also define an array of options as shown below: ? 1 2 3 4 PhoneType: {     title: 'Phone type',     options: [{ Value: '1', DisplayText: 'Home phone' }, { Value: '2', DisplayText: 'Office phone' }, { Value: '2', DisplayText: 'Cell phone' }] } Also, if values of your options are same as display texts, you can write as shown below: ? 1 2 3 4 ClassYear: {     title: 'Phone type',     options: ['1','2','3','4'] } Defining a URL You can define a URL to download array of options: ? 1 2 3 4 PhoneType: {     title: 'Class year',     options: '/Demo/GetPhoneTypes.php' } Your URL must return array of options just like described in the section above. A successfull return value from server is shown below: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 {    "Result":"OK",    "Options":[       {          "DisplayText":"Home phone",          "Value":"1"       },       {          "DisplayText":"Office phone",          "Value":"2"       },       {          "DisplayText":"Cell phone",          "Value":"3"       }    ] } Result can be "OK" or "ERROR". If it's "ERROR", you can supply a "Message" property to show to the user. Defining a function You can define a function that returns an object, an array or a URL string dynamically. Thus, you can show different options for specific records. ? 1 2 3 4 5 6 7 8 9 10 11 12 PhoneType: {     title: 'Phone type',     options: function(data) {         if (data.source == 'list') {             //Return url all options for optimization.              return '/Demo/GetPhoneTypes.php?UserType=0';         }         //This code runs when user opens edit/create form to create combobox.         //data.source == 'edit' || data.source == 'create'         return '/Demo/GetPhoneTypes.php?UserType=' data.record.UserType;     } } If you return a URL as the sample above, jTable downloads options from returned URL just described in the section above. For optimization, jTable caches all option lists based on URL, and gets options from local cache if you return exactly same URL. You can clear cache if you call data.clearCache() method in your function. IMPORTANT: jTable also uses this function to show the related field in the table for each shown record. This is because your record contains Value of the field, not DisplayText and jTable needs to show display text (instead of value) in the table. So, when data.source=='list', returning different URLs causes more than one download to list records in the table. This may be a major performance problem. So, as shown the sample above, return URL of all options while listing (data.source=='list') and return filtered options in edit/create forms (if you need). You may want to return the data from server with ana AJAX request. In this situation, you should get the data from server synhronously since you should return the options from the function. See demo and jQuery async option. The function has data argument which has some fields/methods those can be used to determine returning option list: data.source: This field is used to know why this method is called. Can be 'list', 'create' or 'edit'. data.clearCache(): This method is used to clear cache for currently returning URL. So, you can ensure that your options will be re-downloaded. data.form: This field is used to get a reference to the create/edit form (as jQuery selection). It's valid if data.source is 'create' or 'edit'. data.record: This field is used to get related record with this function call. So, you can return options according to fields of the record (as shown sample). It's valid if data.source is 'list' or 'edit' data.dependedValues: If you define dependsOn option for this field, you can get current value of depended fields using data.dependedValues. See the sample in dependsOn option. dependsOn option and data.dependedValues work as pair and provide you to create cascade dropdowns. See dependsOn option for sample usage. See demo for complete running example. optionsSorting string default: none As default, jTable does not sort options and shows in order which you supplied. This option can be used to automatically sort options. Possible values of this option: value: Sorts options according to value (ascending). value-desc: Sorts options according to value (descending). text: Sorts options according to display text (ascending). text-desc: Sorts options according to display text (descending). sorting boolean default: true Indicates that whether this column will be used to sort the table (If table is sortable). title string default: none Column header in the table and label in the forms for this field. This option is required if the field is shown on the table or create/edit forms. type string default: text Data type for this field. If field is text or number, no need to set type. Other types are: password: Show a password textbox for this field on edit/create forms. textarea: Shows a textarea for this field on edit/create forms. date: A date field (not including time part). A jQueryUI date picker is automatically created for this field on edit/create forms. If a field is date, it can define additional options: displayFormat: Format of date. See jQueryUI datepicker formats. radiobutton: If field is a value from an option list, it can be a combobox (default) or radio button list. If it is a radio button list, set type as radiobutton. You must supply options list for this type. checkbox: To show a checkbox while editing this field. If a field is checkbox, it can define additional options: values: Values for checked/unchecked states. Example: { '0' : 'Passive', '1' : 'Active' }. First value is for unchecked state, second value is for checked state. formText: By default, a checkbox's text changes when user changes the state of the checkbox. If you want to fix the text, you can set the formText option for this field (string). setOnTextClick: By default, when the user clicks the checkbox's text, the state of the checkbox changes. If you do not want that, you can set setOnTextClick to false. hidden: A hidden field can be used hidden fields in edit and create forms. It is not shown on the table. You may want to use defaultValue option with hidden types, thus given default value is automatically set to the hidden field on creating form. See master/child demo for sample usage. visibility string default: 'visible' A column (related to a field) can be showed or hided by user or this option. Values can be: fixed: This column is always visible and can not be hided by the user. visible: This column is visible as default but can be hided by the user. hidden: This column is hidden as default but can be showed by the user. Note: User can open column selection list by right clicking the table header if columnSelectable option is true (it's true as default). width percentage default: '10%' Width of the column for this field in the table. Can be a percantage value (ex: '30%'). It's required if the field is shown on the table. It's best to complete all shown field widths to 100%. NOTE: jTable is designed to fit it's container element, not for a fixed width. So, all columns will be completed to 100%. If you want to fix table's width, set it's container's width.

0 人点赞