您的位置:首页 > 其它

一个用ajax实现表格拖拽

2007-07-15 21:07 369 查看
这里用ajax + servlet 实现一个表格拖 拽

用了JDOM动态记录当前的坐标数 写为XML文档。

需要一个JDOM.jar包

http://download.chinaunix.net/down.php?id=9915&ResourceID=5020&site=1

//JSP页面

<%@page contentType="text/html;charset=gb2312"%>1
<HTML>
<HEAD>
<TITLE>用户登录</TITLE>
</HEAD>
<body onLoad="javascript:document.all.userName.focus();">
<BR>
<style type="text/CSS"> body
{
margin:0px;
}
#aim /*设置目标层样式*/
{
position:absolute;/*控制层的位置所必须的style*/
width:200px;
height:30px;
}
#sourceLayer, #cloneLayer
{
position:absolute;/*控制层的位置所必须的style*/
width:300px;
height:50px;
border:1px solid #666666;
background-color:#CCCCCC;
cursor:move;
}
.docked
{
display:none;
filter:alpha(opacity=100);
}
.actived
{
display:block;
filter:alpha(opacity=70);
}
</style>
<!--<div id="aim">放置范围</div>-->
<div id="div1"></div>
<div id="cloneLayer" class="docked" unselectable="off"></div>
<FORM name="form1" method="post" action="../loginservlet">
<div id="sourceLayer" unselectable="off">
<table width=240 border=0 align="center">
<tr>
<td>
<table width=100% border=0 cellspacing=0 cellpadding=1 bgcolor=99CC99>
<tr>
<td>
<table width=100% border=0 cellspacing=0 cellpadding=0 bgcolor="#f7fff7" align=center valign=top>
<tr>
<td align=left class="ahsPortletTitle" id="title">  
<img src="../graphics/portlethdr1.gif" align="absMiddle">
 
用户登录
</td>
</tr>
<tr>
<td align=center class="normalSmall">
<table width=100% cellspacing=1 cellpadding=1 border=0>
<tr>
<td colspan=2 height=6>
<img src="Machine/graphics/asybase.gif" height=6>
<div id="errMsg" class="errMessage" style="display:none"> </div>
</td>
</tr>
<tr>
<td align=right class=normalSmall> 用户名:
 
</td>
<td align=left>
<input type=text class=textInput name=userName value="">
</td>
</tr>
<tr>
<td align=right class=normalSmall> 密码:
 
</td>
<td align=left>
<input type=password class=textInput name=passWord value="">
</td>
</tr>
<tr>
<td align=right class=normalSmall> </td>
<td align=left class=normalSmall>
<INPUT type="submit" class="normalButton" name="login" value="登陆">
<INPUT type="reset" class="normalButton" name="cancel" value="取消">
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</FORM>
<script type="text/javascript" language="javascript">

<!--

//设置层对象

var aim;

var sourceLayer;

var cloneLayer;

//定义各个层初始位置

var aimX;

var aimY;

var orgnX;

var orgnY;

//拖拽过程中的变量

var draging = false; //是否处于拖拽中

var offsetX = 0; //X方向左右偏移量

var offsetY = 0; //Y方向上下偏移量

var back; //返回动画对象

var thisX ; //当前clone层的X位置

var thisY ; //当前clone层的Y位置

var time ;

var stepX ; //位移速度

var stepY ; //位移速度

//初始化拖拽信息

/*

initAimX 目标x坐标

initAimY 目标y坐标

initOrgnX 拖拽源x坐标

initOrgnY 拖拽源y坐标

*/

//获得层对象

function getLayer(inSource,inClone)

{

//初始化
document.getElementById("div1").innerHTML="";
sourceLayer = document.getElementById(inSource);

cloneLayer = document.getElementById(inClone);

}

function initDrag(initOrgnX,initOrgnY)

{

orgnX = initOrgnX;

orgnY = initOrgnY;

//设置各个开始层的位置

sourceLayer.style.pixelLeft = orgnX;

sourceLayer.style.pixelTop = orgnY;

cloneLayer.style.pixelLeft = orgnX;

cloneLayer.style.pixelTop = orgnY;

}

//准备拖拽

function BeforeDrag()

{

if (event.button != 1)

{

return;

}

cloneLayer.innerHTML = sourceLayer.innerHTML; //复制拖拽源内容

offsetX = document.body.scrollLeft + event.clientX - sourceLayer.style.pixelLeft;

offsetY = document.body.scrollTop + event.clientY - sourceLayer.style.pixelTop;

cloneLayer.className = "actived";

draging = true;

}

//拖拽中

function OnDrag()

{
//如果不在拖拽中
if(!draging)

{

return;

}

//更新位置

event.returnValue = false;

cloneLayer.style.pixelLeft = document.body.scrollLeft + event.clientX - offsetX;

cloneLayer.style.pixelTop = document.body.scrollTop + event.clientY - offsetY;

}

//结束拖拽

function EndDrag()

{

if (event.button != 1)
{

return;

}

draging = false;
//动态的创建目标层
var str="<div id='aim'></div>";
//给目标层加进去
document.getElementById("div1").innerHTML=str;
//得到目标层的对象
aim=document.getElementById("aim");
//更改目标层的座标
aim.style.pixelLeft=cloneLayer.style.pixelLeft;
aim.style.pixelTop=cloneLayer.style.pixelTop;

if (event.clientX >= aim.style.pixelLeft && event.clientX <= (aim.style.pixelLeft + aim.offsetWidth) &&

event.clientY >= aim.style.pixelTop && event.clientY <= (aim.style.pixelTop + aim.offsetHeight))

{

//拖拽层位于目标中,自动定位到目标位置

sourceLayer.style.pixelLeft = aim.style.pixelLeft;

sourceLayer.style.pixelTop = aim.style.pixelTop;

cloneLayer.className = "docked";
//保存XML文档
saveXml(sourceLayer.style.pixelLeft,sourceLayer.style.pixelTop);
/*

** 这里完成之后可以用xml保存当前位置.

** 下次用户进入的时候

** 就初始化源拖拽层为xml当中的数据了

*/

}

else

{

//拖拽位于目标层外,将拖拽源位置复原

thisX = cloneLayer.style.pixelLeft;

thisY = cloneLayer.style.pixelTop;

offSetX = Math.abs(thisX - orgnX);

offSetY = Math.abs(thisY - orgnY);

time = 500;//设置动画时间

stepX = Math.floor((offSetX/time)*20);

stepY = Math.floor((offSetY/time)*20);

if(stepX == 0)

stepX = 2;

if(stepY == 0)

stepY = 2;

//开始返回动画

moveStart();

}

}
function saveXml(x,y)
{
createXMLHttpRequest();
var url="../save?x="+x+"&y="+y+"&title="+document.getElementById('title').innerText;
xmlHttp.open("post",url,true);
xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttp.onreadystatechange=function ()
{
}
xmlHttp.send(null);
}

function moveStart()

{

back = setInterval("MoveLayer();",15);

}

//设置返回的动画效果

function MoveLayer()

{

//位于目标左上

if(cloneLayer.style.pixelLeft <= orgnX && cloneLayer.style.pixelTop <= orgnY)

{

cloneLayer.style.pixelLeft += stepX;

cloneLayer.style.pixelTop += stepY;

//如果位移超过目标则设置速度为pix.并向反方向回移.此处实现了弹簧效果.下同

if(cloneLayer.style.pixelLeft > orgnX)

{

stepX = 1;

}

if(cloneLayer.style.pixelTop > orgnY)

{

stepY = 1;

}

//在X或Y轴上坐标相同则不发生位移

if(cloneLayer.style.pixelLeft == orgnX)

{

stepX = 0;

}

if(cloneLayer.style.pixelTop == orgnY)

{

stepY = 0;

}

if(cloneLayer.style.pixelLeft == orgnX && cloneLayer.style.pixelTop == orgnY)

{

EndMove();

}

}

//位于目标左下

else if(cloneLayer.style.pixelLeft <= orgnX && cloneLayer.style.pixelTop >= orgnY)

{

cloneLayer.style.pixelLeft += stepX;

cloneLayer.style.pixelTop -= stepY;

if(cloneLayer.style.pixelLeft > orgnX)

{

stepX = 1;

}

if(cloneLayer.style.pixelTop < orgnY)

{

stepY = 1;

}

if(cloneLayer.style.pixelLeft == orgnX)

{

stepX = 0;

}

if(cloneLayer.style.pixelTop == orgnY)

{

stepY = 0;

}

if(cloneLayer.style.pixelLeft == orgnX && cloneLayer.style.pixelTop == orgnY)

{

EndMove();

}

}

//位于目标右上

else if(cloneLayer.style.pixelLeft >= orgnX && cloneLayer.style.pixelTop <= orgnY)

{

cloneLayer.style.pixelLeft -= stepX;

cloneLayer.style.pixelTop += stepY;

if(cloneLayer.style.pixelLeft < orgnX)

{

stepX = 1;

}

if(cloneLayer.style.pixelTop > orgnY)

{

stepY = 1;

}

if(cloneLayer.style.pixelLeft == orgnX)

{

stepX = 0;

}

if(cloneLayer.style.pixelTop == orgnY)

{

stepY = 0;

}

if(cloneLayer.style.pixelLeft == orgnX && cloneLayer.style.pixelTop == orgnY)

{

EndMove();

}

}

//位于目标右上

else if(cloneLayer.style.pixelLeft >= orgnX && cloneLayer.style.pixelTop >= orgnY)

{

cloneLayer.style.pixelLeft -= stepX;

cloneLayer.style.pixelTop -= stepY;

if(cloneLayer.style.pixelLeft < orgnX)

{

stepX = 1;

}

if(cloneLayer.style.pixelTop < orgnY)

{

stepY = 1;

}

if(cloneLayer.style.pixelLeft == orgnX)

{

stepX = 0;

}

if(cloneLayer.style.pixelTop == orgnY)

{

stepY = 0;

}

if(cloneLayer.style.pixelLeft == orgnX && cloneLayer.style.pixelTop == orgnY)

{

EndMove();

}

}

//到达目标

else

{

EndMove();

}

}

//停止返回动画

function EndMove()

{

sourceLayer.style.pixelLeft = orgnX;

sourceLayer.style.pixelTop = orgnY;

cloneLayer.style.pixelLeft = orgnX;

cloneLayer.style.pixelTop = orgnY;

cloneLayer.className = "docked";

clearInterval(back);

}

//主拖拽函数

function startDraging(inSource,inClone,initOrgnX,initOrgnY)

{

getLayer(inSource,inClone)

initDrag(initOrgnX,initOrgnY);

sourceLayer.onmousedown = BeforeDrag;

document.onmousemove = OnDrag; //这里如果用cloneLayer,在拖拽中会选中cloneLayer里面内容,进而出现一些bug...

cloneLayer.onmouseup = EndDrag;

}

var xmlHttp;
function createXMLHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
}
function getPosition()
{
createXMLHttpRequest();
var url="../login?title="+document.getElementById("title").innerText;
xmlHttp.open("post",url,true);
xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttp.onreadystatechange=call;
xmlHttp.send(null);
}
function call()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{

var result=xmlHttp.responseXML.getElementsByTagName("result")[0];
var x=result.childNodes[2].firstChild.nodeValue;
var y=result.childNodes[3].firstChild.nodeValue;
//调用

startDraging("sourceLayer","cloneLayer",x,y);

}
else
{
alert(xmlHttp.status);
}
}
}
//调用
getPosition();
//-->

</script>

</body>
</html>
//动态查询SERVLET

package myproduct;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class login extends HttpServlet {
private static final String CONTENT_TYPE = "text/xml; charset=gb2312";

//Initialize global variables
public void init() throws ServletException {
}

//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
//得到头
String title=new String(request.getParameter("title").getBytes("ISO8859-1"),"GBK");
if(title==null)
return ;
String xmlPath=getServletContext().getRealPath("Position.xml");

//得到ID
String pid=dat.getId("ptitle",xmlPath,title.trim());
LoginEntity ent=dat.getValue("Position.xml","pid",pid);
out.println("<?xml version=/"1.0/" encoding=/"gb2312/"?>");
out.println("<root>");
out.println("<result>");
out.println("<pid>"+ent.getPid()+"</pid>");
out.println("<ptitle>"+ent.getPtitle()+"</ptitle>");
out.println("<pixelx>"+ent.getPixelx()+"</pixelx>");
out.println("<pixely>"+ent.getPixely()+"</pixely>");
out.println("</result>");
out.println("</root>");
out.close();
}

//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}

//Clean up resources
public void destroy() {
}
}

//实体类

package myproduct;

public class LoginEntity {
private int pid;
private String ptitle;
private String pixelx;
private String pixely;
public LoginEntity() {
}

public void setPid(int pid) {
this.pid = pid;
}

public void setPtitle(String ptitle) {
this.ptitle = ptitle;
}

public void setPixelx(String pixelx) {
this.pixelx = pixelx;
}

public void setPixely(String pixely) {
this.pixely = pixely;
}

public int getPid() {
return pid;
}

public String getPtitle() {
return ptitle;
}

public String getPixelx() {
return pixelx;
}

public String getPixely() {
return pixely;
}

}

//JDOM公用类

package myproduct;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import java.util.*;
import java.io.*;
public class ParseDom {
public ParseDom() {
}
private static Document dom;
/**
*
* @param path String XML文档的PATH
* @return Document DOM对象
*/
public static Document getDocument(String path)
{
//创建一个sax解析器
SAXBuilder sax=new SAXBuilder();
//通过传过的XML路径进行解析
try {
dom=sax.build(path);
return dom;

} catch (IOException ex) {
ex.printStackTrace();
} catch (JDOMException ex) {
ex.printStackTrace();
}
return null;

}
/**
*
* @param path String XML路径
* @return ArrayList 所有的XML信息
*/
public static List getAllElementValue(String path)
{
//得到一个dom对象
if(dom == null)
{
dom=getDocument(path);
}
//得到根节点
try
{
Element rootElement = dom.getRootElement();
return rootElement.getChildren();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
/**
*
* @param path String XML路径
* @param ElementName String 跟据指定的元素的名称
* @return ArrayList 所有的XML信息
*/
public static List getElementValue(String path,String ElementName)
{
//得到一个dom对象
if(dom == null)
{
dom=getDocument(path);
}
//得到根节点
try
{
Element rootElement = dom.getRootElement();
Element el=rootElement.getChild("position");
List l=el.getChildren(ElementName);
Iterator it= l.iterator();
if(it.hasNext())
{
System.out.println(((Element)it.next()).getChildText("pid"));
}
return null;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;

}
/**
*
* @param path String 要写入的文件
* @return boolean 是否成功
*/
public static boolean xmlOutputer(String path,Document doc)
{
boolean flg=false;
//设置XML文档的格式
Format format=Format.getCompactFormat();
format.setEncoding("gb2312"); //设置XML文件的字符为gb2312
format.setIndent(" ");//设置XML文件缩进为2个空格
XMLOutputter xmlOut=new XMLOutputter(format);
try {
if (doc != null) {
xmlOut.output(doc, new FileOutputStream(path));
flg=true;
}
else
{
flg=false;
}
} catch (IOException ex) {
ex.printStackTrace();
}
return flg;
}

}

//实现查询 和 写入

package myproduct;

import java.util.*;
import org.jdom.*;

public class dat {
public dat() {
}

/**
* 跟据姓名得到ID
* @param Elementname String
* @param path String
* @param ElementValue Stirn
* @return LoginEntity
*/
public static String getId(String Elementname, String path,
String ElementValue) {
//根据节点句子得到一个集合
List ary = ParseDom.getAllElementValue(path);

if (!ary.isEmpty()) {
for (Iterator i = ary.iterator(); i.hasNext(); ) {
Element el = (Element) i.next();
if (el.getChildText(Elementname).trim().equals(ElementValue)) {
return el.getChildTextTrim("pid");
}

}
}
return null;
}

/**
* 跟据ID查出所有的信息
* @param path String
* @param ElementId String
* @return LoginEntity
*/
public static LoginEntity getValue(String path, String ElementId,
String ElementValue) {
//根据节点句子得到一个集合
List ary = ParseDom.getAllElementValue(path);
if (!ary.isEmpty()) {
for (Iterator i = ary.iterator(); i.hasNext(); ) {
Element el = (Element) i.next();
if (el.getChildText(ElementId).trim().equals(ElementValue)) {
LoginEntity log = new LoginEntity();
log.setPid(Integer.parseInt(el.getChildText("pid")));
log.setPtitle(el.getChildText("ptitle"));
log.setPixelx(el.getChildText("pixelX"));
log.setPixely(el.getChildText("pixelY"));
return log;
}

}

}

return null;
}
/**
* 保存
* @param path String
* @param x String
* @param y String
* @param titleValue String
* @param titleName String
* @return boolean
*/
public static boolean saveXml(String path,String x,String y,String titleValue,String titleName)
{
boolean flg=false;
Document dom=ParseDom.getDocument(path);
Element root=dom.getRootElement();
List ary=root.getChildren();
if (!ary.isEmpty()) {
for (Iterator i = ary.iterator(); i.hasNext(); ) {
Element el = (Element) i.next();
if (el.getChildText(titleName.trim()).trim().equals(titleValue.trim())) {
el.getChild("pixelX").setText(x);
el.getChild("pixelY").setText(y);
ParseDom.xmlOutputer(path,dom);
flg=true;
}

}

}
return flg;

}
}
//执行写入的SERVLE

package myproduct;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class save extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";

//Initialize global variables
public void init() throws ServletException {
}

//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();

//得到当前的X座标

String x=request.getParameter("x");

//得到当前的Y座标
String y=request.getParameter("y");

//由于可能是中文进行转码
String title=new String(request.getParameter("title").getBytes("ISO8859-1"),"GBK");
String xmlPath=getServletContext().getRealPath("Position.xml");
if(x !=null || !x.equals("") && y!=null || !y.equals("") && !title.equals("") || title!=null)
{
dat.saveXml(xmlPath,x,y,title,"ptitle");
}

out.close();
}

//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}

//Clean up resources
public void destroy() {
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: