前端时间在论坛里回了fins的一个帖子(http://daoger.javaeye.com/blog/40310)后,有几个网友想看我的例子代码,由于搞自己的一个小系统比较忙,在这里简单说一下dhtmlXGrid的使用心得!
我现在使用的版本是1.2(免费版),我的实现也大部分基于这个免费版,有哪位老兄能提供一份专业版的话更好了!
1.2免费版中的一些功能其实是1.1专业版中的!废话少说,切入正题!
1. 基本使用方法
dhtmlXGrid使用起来还是比较简单的,下面是一段它自带例子中的代码:
- <script>
- mygrid = new dhtmlXGridObject('gridbox');
- mygrid.setImagePath("../imgs/");
- mygrid.setHeader("Sales,Book Title,Author,Price,In Store,Shipping,Bestseller,Date of Publication");
- mygrid.setInitWidths("50,150,100,80,80,80,80,200")
- mygrid.setColAlign("right,left,left,right,center,left,center,center")
- mygrid.setColTypes("dyn,ed,ed,price,ch,co,ra,ro");
- mygrid.getCombo(5).put(2,2);
- mygrid.setColSorting("int,str,str,int,str,str,str,date")
- //mygrid.setColumnColor("white,#d5f1ff,#d5f1ff")
- mygrid.setSkin("xp");
- mygrid.init();
- mygrid.loadXML("../grid.xml");
- </script>
先说一下数据的取得,上面
- mygrid.loadXML("../grid.xml");
是从一个xml文件中取得数据,这个方法的实现基于ajax,下面是dhtmlXCommon.js中的发送请求的实现:
- dtmlXMLLoaderObject.prototype.loadXML = function (filePath, postMode, postVars) {
- this.filePath = filePath;
- try {
- this.xmlDoc = new XMLHttpRequest();
- this.xmlDoc.open(postMode ? "POST" : "GET", filePath, this.async);
- if (postMode) {
- this.xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- }
- this.xmlDoc.onreadystatechange = new this.waitLoadFunction(this);
- this.xmlDoc.send(null || postVars);
- }
- catch (e) {
- if (document.implementation && document.implementation.createDocument) {
- this.xmlDoc = document.implementation.createDocument("", "", null);
- this.xmlDoc.onload = new this.waitLoadFunction(this);
- this.xmlDoc.load(filePath);
- } else {
- this.xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
- this.xmlDoc.open(postMode ? "POST" : "GET", filePath, this.async);
- if (postMode) {
- this.xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- }
- this.xmlDoc.onreadystatechange = new this.waitLoadFunction(this);
- this.xmlDoc.send(null || postVars);
- }
- }
- };
这样你就可以通过这个loadXML()方法向服务器端发送请求,如:
- mygrid.loadXML("aaaa.do?para1=para1&2=para2");
服务器端可以有多种方式处理请求,我使用的java来处理的,接收请求后根据需要构建返回客户端的数据,我采用的是用Jdom生成XML文件流的方式;然后用XMLOutputter将生成的数据文件发送给客户端,dhtmlXGrid 会自己解析数据,显示数据!
下面是发送数据的代码:
- xmlDocument = new Document(rowsElement);
- XMLOutputter outputter = new XMLOutputter();
- try
- {
- response.setContentType("text/xml; charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- outputter.output(xmlDocument, response.getWriter());
- // outputter.output(xmlDocument, System.out);//在控制台输出,查看构建的xml文件是否正确规范
- } catch (IOException e)
- {
- log.error(e);
- try
- {
- response.getWriter().write("<flag>0</flag>");
- } catch (Exception fe)
- {
- }
- }
2. 数据保存及信息反馈
由于版本限制,免费版中没有提供数据保存的api,在专业版中还有用.net和php实现的服务器端实例代码;这一功能我是根据dhtmlXGrid提供的api自己用ajax实现的:
- //deal with data from mygrid
- document.write("<script type='text/javascript' src='script/prototype/infodialog.js'></script>");
- function mydataProcessorObject() {
- var imagesurl = "script/dhtmlXGrid/images/";
- var xmlHttp;//request and response
- var mygrid = new dhtmlXGridObject("gridbox");
- this.dealServer = "";//
- this.querycondithon = "";
- this.dataXml = "";
- this.checkFlag = "";//whether check the cell is null
- this.header = "";
- var newcell;//new record eg."","","","", and so on
- var alertInfotimeout = 3;//alert info show time
- var haveSaved = false;
- this.setDealServer = function (server) {
- this.dealServer = server;
- };
- this.setQueryCondition = function (condition) {
- this.querycondithon = condition;
- };
- /////////////////////////////////////////////////////////
- this.init = function (para) {
- if (para == "query") {
- if (this.querycondithon.length === 0 || this.querycondithon == "" || this.querycondithon == null) {
- mygrid.setImagePath(imagesurl);
- mygrid.enableLightMouseNavigation(true);
- mygrid.loadXML(this.dealServer + "?action=query&ts=" + new Date().getTime());
- } else {
- mygrid.clearAll();
- mygrid.loadXML(this.dealServer + "?action=query&ts=" + new Date().getTime() + "&" + this.querycondithon);
- }
- } else {
- if (para == "add") {
- if (this.readyingAdd()) {
- //mygrid.addRow("A"+(new Date()).valueOf(),['','','','','','','',''],0);
- mygrid.addRow("A" + (new Date()).valueOf(), newcell, 0);
- } else {
- //alert("Exist null cell!");
- openinfodialog("\u5b58\u5728\u7a7a\u5355\u5143\u683c\uff01", 150, 40);
- }
- } else {
- if (para == "save" && !haveSaved) {
- this.readyingSave();
- } else {
- if (para == "delete") {
- var iddel = mygrid.getSelectedId();
- //just whether the record has saved or not
- if (iddel.indexOf("A") === 0) {
- mygrid.deleteSelectedItem();
- openinfodialog("\u6570\u636e\u5df2\u5220\u9664\uff01", 150, 40);
- } else {
- this.loadDelete(iddel);
- }
- }
- }
- }
- }
- };
- /////////////////////////////////////////////////////////
- this.createXMLHttpRequest = function () {
- if (window.ActiveXObject) {
- try {
- xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
- }
- catch (e) {
- try {
- xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- catch (e) {
- }
- }
- } else {
- if (window.XMLHttpRequest) {
- xmlHttp = new XMLHttpRequest();
- }
- }
- };
- /////////////////////////////////////////////////////////
- this.readyingAdd = function () {
- var allitemid = new Array(0);
- allitemid = mygrid.getAllItemIds().split(",");
- var cc = mygrid.getColumnCount();
- newnewcell = new Array(cc + 1);
- var addflag = true;
- if (allitemid.length > 0) {
- for (var i = 0; i < allitemid.length; i++) {
- for (var j = 0; j < cc; j++) {
- var cellValue = mygrid.cells(allitemid[i], j).getValue();
- if (cellValue == null || cellValue.length == 0 || cellValue == "") {
- addflag = false;
- }
- }
- }
- }
- if (addflag) {
- for (var n = 0; n < cc; n++) {
- newcell[n] = "";
- }
- }
- return addflag;
- };
- /////////////////////////////////////////////////////////
- this.readyingSave = function () {
- var allitemid = new Array(0);
- var modiitemid = new Array(0);
- allitemid = mygrid.getAllItemIds().split(",");
- var cc = mygrid.getColumnCount();
- var saveflag = false;
- var blankflag = false;
- var a = 0;
- for (var i = 0; i < allitemid.length; i++) {
- var modiflag = false;
- for (var j = 0; j < cc; j++) {
- if (mygrid.cells(allitemid[i], j).wasChanged()) {
- modiflag = true;
- }
- var cellValue = mygrid.cells(allitemid[i], j).getValue();
- if (cellValue == "" || cellValue.length == 0 || cellValue == null) {
- blankflag = true;
- }
- }
- if (modiflag && !blankflag) {
- modiitemid[a++] = allitemid[i];
- }
- }
- if (this.dealServer.length > 0 && modiitemid.length > 0) {
- this.dataXml = "<?xml version='1.0' encoding='UTF-8'?><data>";
- for (var i = 0; i < modiitemid.length; i++) {
- if (modiitemid[i].length > 0) {
- this.dataXml += "<row id='" + modiitemid[i] + "'>";
- for (var j = 0; j < cc; j++) {
- this.dataXml += "<cell>";
- var mycell = mygrid.cells(modiitemid[i], j).getValue();
- if (mycell.indexOf("<") != -1) {
- this.dataXml += mycell.substring(mycell.indexOf(">") + 1, mycell.indexOf("</"));
- } else {
- this.dataXml += mycell;
- }
- this.dataXml += "</cell>";
- }
- this.dataXml += "</row>";
- }
- }
- this.dataXml += "</data>";
- alert(this.dataXml);
- this.loadSave();
- this.init("query");
- } else {
- if (blankflag) {
- openinfodialog("\u5b58\u5728\u7a7a\u503c\uff01", 100, 40);
- } else {
- //alert("u5df2u7ecfu5b58u50a8u6216u6ca1u6709u6570u636eu6539u52a8uff01");
- openinfodialog("\u5df2\u4fdd\u5b58\u6216\u6ca1\u6709\u53ef\u4fdd\u5b58\u7684\u6570\u636e\uff01", 200, 40);
- }
- }
- };
- /////////////////////////////////////////////////////////
- this.loadSave = function () {
- this.createXMLHttpRequest();
- var url = this.dealServer + "?action=save&ts=" + new Date().getTime();
- xmlHttp.open("POST", url, false);
- xmlHttp.onreadystatechange = this.goCallBackSave;
- xmlHttp.setRequestHeader("Content-Type", "text/xml");
- xmlHttp.setRequestHeader("charset", "UTF-8");
- xmlHttp.send(this.dataXml);
- };
- /////////////////////////////////////////////////////////
- this.goCallBackSave = function () {
- if (xmlHttp.readyState == 4) {
- if (xmlHttp.status == 200) {
- var returnFlag = xmlHttp.responseXML.getElementsByTagName("flag");
- var saveflag = returnFlag[0].firstChild.nodeValue;
- if (saveflag == "1") {
- //alert("u4fddu5b58u6210u529fuff01");
- openinfodialog("\u4fdd\u5b58\u6210\u529f\uff01", 120, 40);
- } else {
- if (saveflag == "0") {
- //alert("u4fddu5b58u5931u8d25!");
- openinfodialog("\u4fdd\u5b58\u5931\u8d25\uff01", 120, 40);
- }
- }
- }
- }
- };
- /////////////////////////////////////////////////////////
- this.loadDelete = function (id) {
- this.createXMLHttpRequest();
- var url = this.dealServer + "?action=delete&id=" + id + "&ts=" + new Date().getTime();
- xmlHttp.open("GET", url, true);
- xmlHttp.onreadystatechange = this.goCallBackDelete;
- xmlHttp.send();
- };
- /////////////////////////////////////////////////////////
- this.goCallBackDelete = function () {
- if (xmlHttp.readyState == 4) {
- if (xmlHttp.status == 200) {
- var returnFlag = xmlHttp.responseXML.getElementsByTagName("flag");
- var delflag = returnFlag[0].firstChild.nodeValue;
- if (delflag == "1") {
- mygrid.deleteSelectedItem();
- //alert("ddddddddd");
- openinfodialog("\u8bb0\u5f55\u5df2\u5220\u9664\uff01", 140, 40);
- } else {
- if (delflag == "0") {
- //alert("u5220u9664u5931u8d25!");
- openinfodialog("\u8bb0\u5f55\u672a\u80fd\u5220\u9664\uff0c\u8bf7\u68c0\u67e5\u539f\u56e0\uff01", 170, 40);
- }
- }
- }
- }
- };
- }
简单说一下思路:通过dhtmlXGrid提供的api wasChange()来判断是否有单元格的数据修改过,如果有修改,在客户端构建要保存数据的xml后,用send方式将其发送到服务器端处理,用服务器端返回的flag标志位提示反馈信息,在提示信息显示的同时,页面中的脚本再向服务器端发送一次查询请求,刷新数据,显示最新数据记录!
还有一个问题是:填写完数据保存时,焦点还在表格中,这时在取数据的时候要注意清除掉<texteare>标签,这样才能取到单元格的值!
代码中的很多方法都是来源于dhtmlXGrid的api,代码有点乱,请尽量参考它自带的文档!
3. 其他问题
操作后的反馈信息我是使用的ouspec 推荐的一个小控件windows_js,现在的版本是1.0;这里是例子:http://prototype-window.xilinus.com/samples.html#
另外,我还使用了yui-ext组件,由于dhtmlXGrid中日期控件是基于YUI开发的,所以两个都使用的时候会有底层方法方面的冲突;我现在的解决方法是把dhtmlXGrid下js文件夹中dhtmlXGrid_excell_calendar.js文件中对event.js的引用替换为YUI包中的event.js;
如果你有更好的解决办法,还请告诉我!
说得有点罗嗦,希望各位网友能听的明白,用起来少走弯路!呵呵!
#################################################################################################
注释:扩展的ajax请求部分如果换成prototype的Ajax.Request会更简洁一些。