JSP+Ajax 添加、刪除多選框_AJAX相關

來源:互聯網
上載者:User

本例是採用JSP + Ajax + 文本來示範多選、全選,添加、刪除、更新checkbox多選框的效果

本例充分展現了利用JavaScript控制HTML DOM以及利用XML http 傳遞資料,利用JSP操作文本的效果

1,JavaScript 用來控制頁面內容的現實與增刪效果;
2,JSP作為後台,對文本進行讀取、寫入、更新等操作;
3,文字格式設定是用來儲存資料的,資料編碼UTF-8;4, 本例子在win32,Red hat Linux 9下 jdk1.5,Tomcat 5.0,Apache 2.5下調試通過,同時相容Firefox 1.0,Opera 8.0,IE6。

本例子的優點:

1,即時建立html對象,所見即所得 (WYSIWYG)的頁面增刪操作。顯示速度加快,增加使用者體驗。
2,XML http傳遞資料是只是一個id或一個表單值,節省頻寬。
3,本例子適合採用XML http方式,所以這個效果實用性強,可是JS/JSP代碼都很簡單。
4,有很多東西可以在其他項目中共用,並且解決了操作文本關於中文字元編碼的問題。 (本例子在中文作業系統運行,所以選擇了GBK編碼,如果OS是英文的則需要另外處理,比如改編碼為UTF-8,或者根據需要另外轉換編碼。)
5,有拖拽以及展開關閉的效果,用cookie記錄了位置以及開啟關閉狀態,可以在某個項目裡用。
6,有豐富的注釋,適合初學者一起探討。

缺點

1,維護調試麻煩,為了這個效果是否值得這樣做?如果採用普通的方式,嵌入一個iframe進來,會不會也可以。
2,代碼沒有更多地最佳化、簡寫,有些地方冗餘。
3,互動設計方面沒有好好地做,這裡主要表示的是技術實現和交流。

源檔案下載:checkbox.rar

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> JSP+Ajax 添加刪除Checkbox執行個體 example test</tITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> <script type="text/javascript"> function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; } //cody by jarry; var emptyCol="",overCol="#f1f1f1",checkedCol="#F4FFF4"; function getAbsoluteLeft( ob ){ if(!ob){return null;} var obj = ob; var objLeft = obj .offsetLeft; while( obj != null && obj .offsetParent != null && obj .offsetParent.tagName != "BODY" ){ objLeft += obj .offsetParent.offsetLeft; obj = obj .offsetParent; } return objLeft ; } // get absolute TOP position function getAbsoluteTop( ob ){ if(!ob){return null;} var obj = ob; var objTop = obj .offsetTop; while( obj != null && obj .offsetParent != null && obj .offsetParent.tagName != "BODY" ){ objTop += obj .offsetParent.offsetTop; obj = obj .offsetParent; } return objTop ; } String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g, "");} function isExist(child,obj){ //obj has element the child; for(var i=0;i<obj.elements.length;i++){ if(obj.elements[i].tagName.toLowerCase()=="input" && obj.elements[i].type=="checkbox"){ if(obj.elements[i].value==child)return true; } } return false; } function validateURL(url){ //validateURL if(url.search(/^[A-Za-z0-9 -]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/)!=0){ return false; //}else if(url.substring(0,4)=="www."){ //return false; }else{ return true; } } function countLength(obj){ if(obj==null)return; var dLen = 0,sLen = 0; for(i=0; i< obj.length; i++ ){ if(obj.charCodeAt(i) > "0" && obj.charCodeAt(i) < "128") sLen+=1; else dLen+=2; } totalLen = sLen+dLen; return totalLen; } var strAll=unescape("%u5168%u9009"); var canAll=unescape("%u53D6%u6D88"); function clickchk(obj){ var allcheck=true; for(var i=0;i<obj.elements.length;i++){ var eli = obj.elements[i]; if(eli.tagName.toLowerCase()=="input" && eli.type=="checkbox"){ eli.parentNode.style.backgroundColor = eli.checked ? checkedCol :""; if(eli.checked==false){allcheck=false;} } } obj.elements["check"].value=allcheck?canAll:strAll; } function addSite(obj){ var url=obj.url.value.trim(); if(url.match(/^\s*$/g) || !validateURL(url)){alert("請輸入正確網址:如mysite.com");obj.url.focus();return;} if(isExist(url,obj)){alert("你添加的網址已經存在列表中");return;} var list=document.getElementById("list"); var chkbox=document.createElement("input"); chkbox.type="checkbox"; chkbox.onclick=function(){clickchk(obj);}//全部選擇後check按鈕顯示取消; chkbox.value=url; chkbox.name="url_chkbox"; var hr=document.createElement("hr"); hr.size="0";hr.style.borderTop="1px solid gray"; var txt=document.createTextNode(url); var div=document.createElement("div"); div.appendChild(chkbox); div.appendChild(txt); div.style.borderBottom="1px dashed gray"; div.style.padding="5px"; //div.appendChild(hr); //div.style.backgroundColor = "olive"; div.onmouseover=function(){ showDelete(this); } div.onmouseout=function(){ hideDelete(this); } list.appendChild(div); //end add; //如果已經添加了多選框則去掉禁用; if(obj.check.disabled==true){ obj.check.disabled=false; obj.recheck.disabled = false; obj.remove.disabled=false; } return false; } function checkall(obj){//全選or取消全選; var chk=obj.elements["check"]; for(var i=0;i<obj.elements.length;i++){ if(obj.elements[i].tagName.toLowerCase()=="input" && obj.elements[i].type=="checkbox"){ if(chk.value==strAll){//check all checkbox input; obj.elements[i].checked=true; obj.elements[i].parentNode.style.backgroundColor = checkedCol; }else{ obj.elements[i].checked=false; obj.elements[i].parentNode.style.backgroundColor = emptyCol; } } } if($('list').childNodes.length<=1)return; chk.value=chk.value==canAll?strAll:canAll; //更改全選/取消的顯示; } function reverseCheck(obj){ var chk=obj.elements["check"]; for(var i=0;i<obj.elements.length;i++){ if(obj.elements[i].tagName.toLowerCase()=="input" && obj.elements[i].type=="checkbox"){ obj.elements[i].checked = obj.elements[i].checked ? false : true; } clickchk(obj); } } function del(list,obj){ //刪除list的內容 var candel=false; var i=list.childNodes.length; var end = -1; while( i > end ){ //如果存在child var s=list.childNodes[i]; if(typeof(s)!="undefined" && s.tagName){ try{ //如果child的類型不為空白; var tgname = s.tagName.toUpperCase(); if(tgname != "DIV" || s.childNodes.length <=0 )return; //子集是div且還有子集 var s1 = s.childNodes[0]; if( s1.type.toLowerCase() =="checkbox" && s1.checked==true ){ //如果該子集裡的checkbox選中,那麼刪除改子集(div); candel = true; list.removeChild(s); } }catch(ex){ //alert(ex.toString()); } } i--; } if(candel==false){alert("請選擇你要刪除的選項")} isDisabledButton(); } function isDisabledButton(){ var objform=document.sitelist; var list=$("list"); var hasDivChild = false; if(list.childNodes.length>0 ){ for(var i=0;i<list.childNodes.length;i++){ var s=list.childNodes[i]; if( typeof(s)!="undefined" && s.tagName) { if(s.tagName.toUpperCase()=="DIV") hasDivChild = true; } } } objform.check.disabled= hasDivChild?false:true; objform.recheck.disabled= hasDivChild?false:true; objform.check.value=strAll; objform.remove.disabled= hasDivChild?false:true; } function delSingle(objparent,objdel,objchild){ objparent.removeChild(objchild); objdel.style.display="none"; // isDisabledButton(); } function editSingle(objparent,objedit,objchild){ function makeLink(text , tag){ var temobj = document.createElement(tag); temobj.style.marginLeft="5px"; temobj.style.marginRight="5px"; temobj.style.textDecoration="underline";temobj.style.cursor="pointer"; temobj.appendChild( document.createTextNode(text) ); return temobj; } try{ var secondChild = objchild.childNodes[1]; var url = secondChild; var urlStr = url.nodeValue ;//? url.nodeValue : url.toString() ; if(urlStr==null || urlStr.trim=="")return; var editorPanel = document.createElement("span"); objchild.removeChild(url); var editor = document.createElement("input"); editor.type="text"; //var maxLen = parseInt(objparent.style.width) - 250; var maxLen = 50; var thisLen = parseInt( countLength(urlStr) ); editor.size = maxLen > thisLen ? thisLen : maxLen; editor.value = urlStr; editor.select(); editor.onmouseover=function(){this.select();} var update = makeLink("update","font");update.title="更新"; update.onclick=function(){ //updateContens(); var newvalue = editor.value; if(newvalue.trim() == ""){editor.focus();return;} objchild.removeChild(objchild.childNodes[1]); objchild.appendChild(document.createTextNode(newvalue)); } var cancle = makeLink("cancle","font");cancle.title="取消"; cancle.onclick=function(){ objchild.removeChild(objchild.childNodes[1]); objchild.appendChild(url); } //add to editorPanel; editorPanel.style.fontSize="11px"; editorPanel.style.color="blue"; editorPanel.appendChild(editor); editorPanel.appendChild(update); editorPanel.appendChild(document.createTextNode("|")); editorPanel.appendChild(cancle); //add to objchild; objchild.appendChild(editorPanel); }catch(ex){ alert(ex.toString()); }finally{ // } } var currentDiv; function showDelete(self){ self.style.backgroundColor = overCol; currentDiv = self; var theid = "del_icon"; if(!$(theid)){ var delDiv=document.createElement("div"); delDiv.id=theid; var d=delDiv; d.style.textAlign="center";d.style.fontSize="11px"; var edit = document.createElement("span"); edit.title="編輯此條";edit.style.textDecoration="underline"; edit.onclick=function(){ editSingle(currentDiv.parentNode,this.parentNode,currentDiv); } var del = document.createElement("span"); del.title="刪除此條";del.style.textDecoration="underline"; del.onclick=function(){ delSingle(currentDiv.parentNode,this.parentNode,currentDiv); } edit.appendChild(document.createTextNode("edit")); d.appendChild(edit); d.appendChild(document.createTextNode(" | ")); del.appendChild(document.createTextNode("delete")); d.appendChild(del); d.style.width="80px"; d.style.lineHeight="20px"; d.style.color="blue"; // d.style.zIndex="-10"; // d.style.backgroundColor="green"; document.body.appendChild(d); $(theid).onmouseover=function(){ currentDiv.style.backgroundColor = overCol; this.style.display=""; //mouseOndeleteDiv=true; } // $(theid).style.cursor="pointer"; } if($(theid)){ $(theid).style.display=""; var l= getAbsoluteLeft(self) + self.offsetWidth - 80; var t= getAbsoluteTop(self) + 5; var scrollT = self.parentNode.scrollTop;//減去出現捲軸的高度; var t= getAbsoluteTop(self) + 5 - scrollT; $(theid).style.position="absolute"; $(theid).style.left = l+"px"; $(theid).style.top = t+"px"; } } function hideDelete(self){ var theid = "del_icon"; if( $(theid) ){ self.style.backgroundColor = self.childNodes[0].checked?checkedCol:emptyCol; $(theid).style.display="none"; } } </script> </hEAD> <BODY> <style> .drag{position:absolute;width:600px; background-color:#f1f1f1; filter:alpha(opacity=100); -moz-opacity:1.0; opacity:1.0; } .da{width:100%;background-color:gray;cursor:move;font-size:14px;vertical-align:middle;line-height:30px} .max_min_btn{float:right;color:red;cursor:pointer;font-size:9pt;width:50px;line-height:30px;text-align:center;} #list{border-top:2px ridge #9A9898;border-left:2px ridge #9A9898;border-bottom:1px solid #D4D0C8;border-right:1px solid #D4D0C8;background:white;width:578px;height:350px;margin:10px;overflow:auto} .shadowBottom{margin-left:6px;height:5px;background:gray;font-size:0px;line-height:0px;filter:alpha(opacity=55);-moz-opacity:0.55;opacity:0.55;} </style> <pre> 本例是採用JSP + Ajax + 文本來示範多選、全選,添加、刪除、更新checkbox多選框的效果。 本例充分展現了利用JavaScript控制HTML DOM以及利用XML http 傳遞資料,利用JSP操作文本的效果。 1,JavaScript 用來控制頁面內容的現實與增刪效果; 2,JSP作為後台,對文本進行讀取、寫入、更新等操作; 3,文字格式設定是用來儲存資料的,資料編碼UTF-8;4, 本例子在win32,Red hat Linux 9下 jdk1.5,Tomcat 5.0,Apache 2.5下調試通過,同時相容Firefox 1.0,Opera 8.0,IE6。 線上說明文檔 http://jiarry.blogchina.com/5599587.html靜態頁面示範地址:http://jarryli.googlepages.com/checkbox_test.html (詳細的說明,隨後補充)源檔案下載地址:http://jarryli.googlepages.com/checkbox.rar 另外之前做的 PHP+Ajax 發帖程式執行個體:http://jiarry.blogchina.com/5555296.html 源碼下載:http://jarryli.googlepages.com/post_ajax.rar JSP登入證碼無重新整理提示:http://jiarry.blogchina.com/5287654.html 源碼下載:http://jarryli.googlepages.com/imgValidate.rar <div class="drag" rel="drag" id="siteMainDarg" onMouseDown="dargit(this,event);"> <div class="da" ><span class="max_min_btn" id="max_min" ><font >2</font>CLOSE</span>  拖拽區</div> <div id="sitelistDiv" > <form name="sitelist" onSubmit="return addSite(this);" ><br clear="all">   http:// <INPUT TYPE="text" size="30" NAME="url" onmouseover="this.focus()"> <INPUT TYPE="button" NAME="add" value="添加網址至列表" onClick="addSite(this.form)"> <div id="list"> <div onMouseOver="showDelete(this);" onmouseout="hideDelete(this);" ><input type=checkbox value="example.com" name="url_chkbox" onClick="clickchk(this.form)">example1.com </div> <div onMouseOver="showDelete(this);" onMouseOut="hideDelete(this);" ><input type=checkbox value="example.com" name="url_chkbox" onClick="clickchk(this.form)">example2.com </div> </div>   <INPUT TYPE="button" NAME="check" value="全選" disabled onClick="checkall(this.form)">  <input type="button" value="反選" name="recheck" disabled onclick="reverseCheck(this.form)">  <INPUT TYPE="button" NAME="remove" disabled value="刪除" onClick="del($('list'),this.form)"> </form> </div> <div class="shadowBottom"> </div> </div> Cody by JarryLi@gmail.com; CopyRight?Jarry,All right reserved! 本例僅供個人蔘考,引用請保留著作權資訊。謝謝! homepage:jiarry.126.com Blog:http://jiarry.blogchina.com <script> //頁面載入時初始化 function init(l,f){ var list=l; f.check.disabled=list.childNodes.length>1?false:true; f.recheck.disabled=list.childNodes.length>1?false:true; f.check.value=strAll; f.remove.disabled=list.childNodes.length>1?false:true; } window.onload=function(){ init($("list"),document.sitelist); } activeCookie = true; if(document.cookie==null){ //alert("cookie沒有開啟!"); activeCookie = false; } function getCookie(name) { if( !activeCookie ) return; var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function setCookie(name , value) { if( !activeCookie ) return; var expdate = new Date(); expdate.setTime(expdate.getTime() + (365*24*120)); document.cookie=""+ name + "=" + value +";expires="+ expdate.toGMTString(); } var theLeft = getCookie("siteMainDargLeft")!=null ? getCookie("siteMainDargLeft") : 10; var theTop = getCookie("siteMainDargTop")!=null ? getCookie("siteMainDargTop") : 10; var listDivDisplay = getCookie("sitelistDivDisplay")!=null ? getCookie("sitelistDivDisplay") : ""; $("siteMainDarg").style.top = theTop; $("siteMainDarg").style.left = theLeft; $("sitelistDiv").style.display = listDivDisplay; //cookie end; //////////////////////// var d_width = 550; var d_height = 30; var ey=0,ex=0,lx=0,ly=0,canDrg=false,thiso=null;// var x, y,rw,rh; var divs=document.getElementsByTagName("div"); for (var i=0;i<divs.length;i++){ if(divs[i].getAttribute("rel")=="drag"){ divs[i].onmousemove=function(){ thismove(this);//即時得到當前對象與滑鼠的值以判斷拖動及關閉地區; } } } function thismove(o){ rw = parseInt(x)-parseInt(getAbsoluteLeft(o)); rh = parseInt(y)-parseInt(getAbsoluteTop(o)); } function dargit(o,e){ thiso = o; canDrg = true; if(!document.all){ lx = e.clientX; ly = e.clientY; }else{ lx = event.x; ly = event.y; } try{//設定漸層色; if(rh<=d_height && rw<d_width &&rh>0){//設定在拖動地區 if(document.all)thiso.filters.Alpha.opacity=80; else thiso.style.MozOpacity=80/100; } }catch(e){ } st(o); } document.onmousemove = function(e){ if(!document.all){ x = e.clientX; y = e.clientY; }else{ x = event.x; y = event.y; } if(canDrg){ if(rh<=d_height && rw<d_width &&rh>0){//如果要設定拖動地區可以作判斷 var ofsx = x - lx; thiso.style.left = (parseInt(thiso.style.left) + ofsx) +"px"; lx = x; var ofsy = y - ly; thiso.style.top = (parseInt(thiso.style.top) + ofsy) +"px"; ly = y; }else{ canDrg=false; } } } document.onmouseup=function(){ canDrg=false;//拖拽變數設為false try{ if(document.all)thiso.filters.Alpha.opacity=100; else thiso.style.MozOpacity=100; }catch(e){} if(document.all && thiso != null){ thiso.releaseCapture(); thiso = null; } } function st(o){ if(rh <= d_height && rw >= d_width){ canDrg=false; showHide($("sitelistDiv")); } } function showHide(obj,self){ obj.style.display = obj.style.display=="none"?"":"none"; //$("del_icon").display="none"; var icon = "1"; var text = "OPEN"; if(obj.style.display==""){ icon = "2"; text = "CLOSE"; } $("max_min").childNodes[0].innerHTML = icon; $("max_min").childNodes[1].nodeValue = text; } window.onunload = function(){ setCookie("siteMainDargLeft",getAbsoluteLeft( $("siteMainDarg") ) ); setCookie("siteMainDargTop",getAbsoluteTop( $("siteMainDarg") ) ); setCookie("sitelistDivDisplay",$("sitelistDiv").style.display ); } </script> </bODY> </hTML>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

由於時間有限,難免有很多問題,希望大家提出來。其實本例做的並不怎麼好,拿出來希望眾位多多入指點,同時也希望對同樣是初學者的朋友來說有協助,也希望大家一起交流進步,謝謝!:p

另外之前做的有關Ajax的東東,順便請供參考,謝謝!

PHP+Ajax 發帖程式執行個體: http://jiarry.blogchina.com/5555296.html 
源碼下載: post_ajax.rar

JSP登入證碼無重新整理提示: http://jiarry.blogchina.com/5287654.html 
源碼下載: imgValidate.rar

代碼沒有整理,最佳化,所以本例子只供大家交流參考用,希望可以通過這種方式得到各位的協助,謝謝!

經典論壇討論
http://bbs.blueidea.com/viewthread.php?tid=2673442

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.