//构造方法,var后面的Myoo相当于类名
var Myoo = function()
{
this.param = 100 ;//相当于定义属性
this.hello = function(){
}
this.hi = function(i,j){
}
var ii = 10 ; //这个ii在外部不可见,只能通过getI或者setI方法来改变。
this.getI = function(){return ii ;}
this.setI = function(i){ii = i ;}
}
Myoo.prototype.send = function(){}
//还可以像上面那样来声明方法,这样在new对象的时候,
//send方法并不会装载到对象中去!但是对象仍然可以使用send方法。
------------------------------
//类级别对象的定义方式
NewMyoo.JJ = 10 ;
NewMyoo.showPopup = function(){
alert("123");
}
function test()
{
var my = new Myoo() ;//new的过程相当于执行上面的函数。
//my.param值就是100
//my.hello()也就是相当于调用对象方法了。
//my.hi(i,j)
//调用类级对象
NewMyoo.JJ;
NewMyoo.showPopup
}
------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<input type="button" value="test" onclick="testoo()"/>
<script type="text/javascript">
var MyOO = function(i,j){
this.i = i;
this.j = j;
var pi;
this.setPI = function(pppi){
pi = pppi;
}
this.getPI = function(){
return pi;
}
}
MyOO.prototype.show = function(){
alert("i:" + this.i + " j:" + this.j);
}
MyOO.SSI = 100;
MyOO.showSSI = function(){
alert(MyOO.SSI);
}
function testoo(){
var my1 = new MyOO(1,2);
var my2 = new MyOO(100,200);
my1.show();
my2.show();
my1.setPI(10);
alert("my1.getPI():" + my1.getPI());
my2.setPI(1000);
alert("my1.getPI():" + my1.getPI());
alert("my2.getPI():" + my2.getPI());
MyOO.showSSI();
//my1.showSSI();
//my2.showSSI();
alert("my1.SSI:" + my1.SSI);
alert("my2.SSI:" + my2.SSI);
my1.SSI = 999;
my2.SSI = 888;
MyOO.showSSI();
alert("my1.SSI:" + my1.SSI);
alert("my2.SSI:" + my2.SSI);
}
</script>
</body>
</html>
类级别属性对象不能访问,但是可以通过动态赋值的方式给
对象增添属性。
-----------------------------------------------
优化过的XMLHttpRequest的封装方法:
var MyXMLHttpRequest = function(){
this.xmlhttp = null; //需要创建的XMLHttpRequest对象
if(window.XMLHttpRequest){
//for mozillar and IE7,对于IE7,可以直接得到XMLHttpRequest对象
this.xmlhttp = new XMLHttpRequest();
if(window.overrideMimeType){
this.xmlhttp.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
//for IE6 and IE5
var microsoft = ['MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
for(var i=0; i<microsoft.length; i++){
try{
this.xmlhttp = new ActiveXObject(microsoft[i]);
break;
}catch(e){
}
}
} else{
alert("Can't Create XMLHttpRequest Objcet");
}
}
//method:post还是get方法;url:地址;data:发什么样的数据过去;usercallback:回调方法名称(状态改变后去调用)
//failcallback:错误处理
MyXMLHttpRequest.prototype.send = function(method,url,data,usercallback,failcallback){
if(this.xmlhttp){
var tempxmlhttp = this.xmlhttp;
this.xmlhttp.onreadystatechange = function(){
if(tempxmlhttp.readyState == 4){
if(tempxmlhttp.status == 200){
if(usercallback){
usercallback(tempxmlhttp.responseText,tempxmlhttp.responseXML);
} else{
alert("Not Set UserCallBack Function");
alert("The Responsetext is " + tempxmlhttp.responseText);
}
} else{
if(failcallback){
failcallback(tempxmlhttp.status);
} else{
alert("Server Error.The Http Status is:" + tempxmlhttp.status);
}
}
}
}
if(method.toUpperCase() != "GET" && method.toUpperCase() != "POST"){
alert("The Http method must be \"GET\" OR \"POST\"!");
return false;
}
if(url == null || url.length == 0){
alert("Must give the url address!");
return false;
}
//在url地址的后面拼一个时间戳,由于IE会对同一个URL地址缓存,为了防止再次访问读取的不是
//服务器端信息而是缓存的问题,所以要在url的最后加上时间戳保证每一次的url请求地址都是不
//一样的
else{
if(url.indexOf("?") >= 0){
url = url + "&t=" + (new Date()).valueOf();
} else{
url = url + "?t=" + (new Date()).valueOf();
}
}
this.xmlhttp.open(method,url,true);
if(method.toUpperCase( ) == "POST"){
this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
this.xmlhttp.send(data);
} else{
alert("Not Create XMLHttpRequest Object.Can't Send Data");
}
}
---------------------------------------------------------
学生管理系统服务器端代码:
import java.io.*;
import java.util.Random;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.*;
import javax.servlet.http.*;
public class StudentListServlet extends HttpServlet {
private HashMap studentMap;
public void init(javax.servlet.ServletConfig servletConfig)
throws javax.servlet.ServletException{
studentMap = new HashMap();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equals("add")) {
addStudent(request, response);
} else if(action.equals("delete")) {
deleteStudent(request, response);
} else if(action.equals("modify")){
modifyStudent(request, response);
}
}
protected void dPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void addStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Student student = new Student();
student.setName(request.getParameter("name"));
student.setNumber(request.getParameter("number"));
student.setClassName(request.getParameter("classname"));
String uniqueID = storeStudent();
student.setUid(uniqueID);
StringBuffer xml = new StringBuffer("<result><uniqueID>");
xml.append(uniqueID);
xml.append("</uniqueID>");
xml.append("<status>1</status>");
xml.append("</result>");
studentMap.put(uniqueID,student);
sendResponse(response, xml.toString());
printStundets();
}
protected void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uid = request.getParameter("id");
studentMap.remove(uid);
StringBuffer xml = new StringBuffer("<result><uniqueID>");
xml.append(uid);
xml.append("</uniqueID>");
xml.append("<status>1</status>");
xml.append("</result>");
sendResponse(response, xml.toString());
printStundets();
}
protected void modifyStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uid = request.getParameter("id");
StringBuffer xml = new StringBuffer("<result><uniqueID>");
if(false){
Student student = (Student) studentMap.get(uid);
student.setName(request.getParameter("name"));
student.setNumber(request.getParameter("number"));
student.setClassName(request.getParameter("classname"));
xml.append(uid);
xml.append("</uniqueID>");
xml.append("<status>1</status>");
xml.append("</result>");
} else{
xml.append(uid);
xml.append("</uniqueID>");
xml.append("<status>0</status>");
xml.append("</result>");
}
sendResponse(response, xml.toString());
printStundets();
}
private String storeStudent() {
String uniqueID = "";
Random randomizer = new Random(System.currentTimeMillis());
for(int i = 0; i < 8; i++) {
uniqueID += randomizer.nextInt(9);
}
return uniqueID;
}
private void sendResponse(HttpServletResponse response, String responseText)
throws IOException {
response.setContentType("text/xml");
response.getWriter().write(responseText);
}
private void printStundets(){
System.out.println("Current Student List:" + studentMap.size() + " students");
System.out.println("uid\t\t\tname\tnumber\tclassname");
Iterator iter = studentMap.keySet().iterator();
while(iter.hasNext()){
String uid = (String) iter.next();
Student student = (Student) studentMap.get(uid);
System.out.println(uid+"\t"+student.getName()+"\t\t"+student.getNumber()+"\t\t"+student.getClassName());
}
}
}
class Student{
private String name;
private String number;
private String className;
private String uid;
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public void setClassName(String className) {
this.className = className;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public String getClassName() {
return className;
}
public String getUid() {
return uid;
}
}
-----------------------------------------------
学生管理系统网页StudentList.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Student List</title>
</head>
<body>
<script src="xmlhttp.js"></script>
<script type="text/javascript">
var name;
var number;
var classname;
var action;
var EMP_PREFIX = "emp-";
var oralData = new Array();
function addStudent() {
name = document.getElementById("name").value;
number = document.getElementById("number").value;
classname = document.getElementById("classname").value;
action = "add";
if(name == "" || number == "" || classname == "") {
return;
}
var url = "StudentListServlet?"
+ createAddQueryString(name, number, classname, "add");
var xmlhttp = new MyXMLHttpRequest();
xmlhttp.send("GET",url,null,handleAddStateChange);
}
function createAddQueryString(name, title, department, action) {
var queryString = "name=" + name
+ "&number=" + number
+ "&classname=" + classname
+ "&action=" + action;
return queryString;
}
function handleAddStateChange(responseText,responseXML) {
updateStudentList(responseXML);
clearInputBoxes();
}
function updateStudentList(responseXML) {
var status = responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
status = parseInt(status);
if(status != 1) {
return;
}
var row = document.createElement("tr");
var uniqueID = responseXML.getElementsByTagName("uniqueID")[0].firstChild.nodeValue;
row.setAttribute("id", EMP_PREFIX + uniqueID);
row.appendChild(createCellWithText(name,"name"+uniqueID));
row.appendChild(createCellWithText(number,"number"+uniqueID));
row.appendChild(createCellWithText(classname,"classname"+uniqueID));
var modifyButton = document.createElement("input");
modifyButton.setAttribute("type", "button");
modifyButton.setAttribute("value", "修改");
modifyButton.setAttribute("id", "modify"+uniqueID);
modifyButton.onclick = function () { modifyStudent(uniqueID); };
var cell = document.createElement("td");
cell.appendChild(modifyButton);
row.appendChild(cell);
var submitButton = document.createElement("input");
submitButton.setAttribute("type", "button");
submitButton.setAttribute("value", "提交");
submitButton.setAttribute("id", "submit"+uniqueID);
submitButton.setAttribute("disabled", true);
submitButton.onclick = function () { submitStudent(uniqueID); };
var cell = document.createElement("td");
cell.appendChild(submitButton);
row.appendChild(cell);
var deleteButton = document.createElement("input");
deleteButton.setAttribute("type", "button");
deleteButton.setAttribute("value", "删除");
deleteButton.onclick = function () { deleteStudent(uniqueID); };
var cell = document.createElement("td");
cell.appendChild(deleteButton);
row.appendChild(cell);
document.getElementById("studentList").appendChild(row);
updateEmployeeListVisibility();
}
function createCellWithText(text,idText) {
var input = document.createElement("input");
input.setAttribute("type","text");
input.setAttribute("value",text);
input.setAttribute("id",idText);
input.setAttribute("disabled",true);
var cell = document.createElement("td");
cell.appendChild(input);
return cell;
}
function updateEmployeeListVisibility() {
var employeeList = document.getElementById("studentList");
if(employeeList.childNodes.length > 0) {
document.getElementById("studentListSpan").style.display = "";
}
else {
document.getElementById("studentListSpan").style.display = "none";
}
}
function clearInputBoxes() {
document.getElementById("name").value = "";
document.getElementById("number").value = "";
document.getElementById("classname").value = "";
}
function modifyStudent(id){
var nameNode = document.getElementById("name"+id);
nameNode.removeAttribute("disabled");
var oralName = nameNode.getAttribute("value");
var numberNode = document.getElementById("number"+id);
numberNode.removeAttribute("disabled");
var oralNumber = numberNode.getAttribute("value");
var classnameNode = document.getElementById("classname"+id);
classnameNode.removeAttribute("disabled");
var oralClassName = classnameNode.getAttribute("value");
var modifyNode = document.getElementById("modify"+id);
modifyNode.setAttribute("disabled",true);
var submitNode = document.getElementById("submit"+id);
submitNode.removeAttribute("disabled");
oralData.unshift({id:id,name:oralName,number:oralNumber,classname:oralClassName})
}
function submitStudent(id){
var name = document.getElementById("name"+id).value;
var number = document.getElementById("number"+id).value;
var classname = document.getElementById("classname"+id).value;
var url = "StudentListServlet?" + "name=" + name
+ "&number=" + number
+ "&classname=" + classname
+ "&id=" + id
+ "&action=modify";
var xmlhttp = new MyXMLHttpRequest();
xmlhttp.send("GET",url,null,handleSbumityStateChange);
var modifyNode = document.getElementById("modify"+id);
modifyNode.removeAttribute("disabled");
var submitNode = document.getElementById("submit"+id);
submitNode.setAttribute("disabled",true);
}
function handleSbumityStateChange(responseText,responseXML) {
submitEmployeeFromList(responseXML);
}
function submitEmployeeFromList(responseXML) {
var status = responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
var uniqueID = responseXML.getElementsByTagName("uniqueID")[0].firstChild.nodeValue;
var nameNode = document.getElementById("name"+uniqueID);
var numberNode = document.getElementById("number"+uniqueID);
var classnameNode = document.getElementById("classname"+uniqueID);
var index;
for(var i=0;i<oralData.length;i++){
if(oralData[i].id == uniqueID){
index = i;
break;
}
}
status = parseInt(status);
if(status != 1) {
//恢复原来的数据
// nameNode.setAttribute("value",oralData[index].name);
// numberNode.setAttribute("value",oralData[index].number);
// classnameNode.setAttribute("value",oralData[index].classname);
nameNode.value = oralData[index].name;
numberNode.value = oralData[index].number;
classnameNode.value = oralData[index].classname;
}
oralData.splice(index,1);
nameNode.setAttribute("disabled","true");
numberNode.setAttribute("disabled","true");
classnameNode.setAttribute("disabled","true");
}
function deleteStudent(id) {
var url = "StudentListServlet?"
+ "action=delete"
+ "&id=" + id;
var xmlhttp = new MyXMLHttpRequest();
xmlhttp.send("GET",url,null,handleDeleteStateChange);
}
function handleDeleteStateChange(responseText,responseXML) {
deleteEmployeeFromList(responseXML);
}
function deleteEmployeeFromList(responseXML) {
var status = responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
var deleteID = responseXML.getElementsByTagName("uniqueID")[0].firstChild.nodeValue;
status = parseInt(status);
if(status != 1) {
return;
}
var rowToDelete = document.getElementById(EMP_PREFIX + deleteID);
var employeeList = document.getElementById("studentList");
employeeList.removeChild(rowToDelete);
updateEmployeeListVisibility();
}
</script>
<h1>学生管理系统</h1>
<table width="80%" border="0">
<tr>
<td>姓名: <input type="text" id="name" /></td>
<td>学号: <input type="text" id="number"/></td>
<td>班级: <input type="text" id="classname"/></td>
</tr>
</table>
<input type="button" value="增加" onclick="addStudent()" />
<span id="studentListSpan" style="display:none;">
<h2>学生:</h2>
<table border="1" width="80%">
<tbody id="studentList"></tbody>
</table>
</span>
</body>
</html>
===================================================================
鼠标放上去后会显示一个文本框,里面有书籍信息
服务器端:
/**
* Created by IntelliJ IDEA.
* User: xingxing
* Date: 2007-3-13
* Time: 0:04:31
* To change this template use File | Settings | File Templates.
*/
import java.io.PrintWriter;
import java.util.HashMap;
public class ToolTip extends javax.servlet.http.HttpServlet {
private HashMap messageMap;
private enum Books{book1,book2,book3,book4,book5,book6;
public static boolean isBookID(String id){
for(Books book : Books.values()){
if(id.equals(book.name())){
return true;
}
}
return false;
}
};
public void init(javax.servlet.ServletConfig servletConfig) throws javax.servlet.ServletException{
messageMap = new HashMap();
messageMap.put(Books.book1.name(),"本书目前已有翻译版在国内销售。本书除了介绍AJAX的基本知识以外,在跨浏览 器实现XML处理和Webservice处理上做了详细介绍,也有一个如何建立自己的Gmail的示例,另外还介绍了三个分别为PHP,JAVA和. NET平台服务的AJAX服务器端框架。");
messageMap.put(Books.book2.name(),"号称国内第一本AJAX的图书,在国外也很受欢迎的一本书。个人认为书中比较有用的是介绍了很多AJAX开发的辅助工具,同时有过个实用的AJAX示例。 ");
messageMap.put(Books.book3.name(),"国内已有此书的翻译版。本书比较短小精悍,其中比较特色的是介绍了如何建立一个 自己的Google Maps,并在AJAX UI方面做了较多描述,另外简要介绍了一些浏览器端AJAX框架,以及AJAX和PHP联合开发的问题。");
messageMap.put(Books.book4.name(),"本书编排和版面设计上比较有特色。内容上即介绍了AJAX的基本知识,也介绍了 AJAX的一些框架。比较有特色的部分是给出了AJAX开发的十个需要了解的问题以及一些有用的AJAX资源。");
messageMap.put(Books.book5.name(),"国内已有此书的翻译版本。一本将近700页的AJAX图书,和其他AJAX图书 相比分量很重,介绍内容非常广泛。可以作为一本AJAX的参考书。书中最后介绍了目前几乎所有的AJAX浏览器及服务器端框架,对于大家选择AJAX框架 有一定的帮助。");
messageMap.put(Books.book6.name(),"国外著名IT出版社O'Reilly的AJAX图书,国内有影印版。该书以一个 个Hack条目来介绍AJAX,其中有一半的篇幅介绍了我们前面提到的几个流行的AJAX框架:DWR,Ruby On Rails,Rico,script.aculo.us。同时还有一些实用的示例供大家参考。");
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Contorl","no-cache");
PrintWriter out = response.getWriter();
String id = request.getParameter("id");
String info;
if(Books.isBookID(id)){
info = (String) messageMap.get(id);
} else{
info = "没有该书的介绍信息";
}
out.println("<book>");
out.println("<info>" + info + "</info>");
out.println("</book>");
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
doPost(request,response);
}
}
客户端:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<p>AJAX图书介绍:</p>
<p><span id="book1" onmouseover="show(this,event)" onmouseout="clearinfo()">Professional Ajax(AJAX高级程序设计)</span></p>
<p><span id="book2" onmouseover="show(this,event)" onmouseout="clearinfo()">Foundations Of AJAX(AJAX基础教程)</span></p>
<p><span id="book3" onmouseover="show(this,event)" onmouseout="clearinfo()">Pragmatic AJAX(AJAX修炼之道-Web2.0入门)</span></p>
<p><span id="book4" onmouseover="show(this,event)" onmouseout="clearinfo()">AJAX For DUMMIES(AJAX傻瓜教程)</span></p>
<p><span id="book5" onmouseover="show(this,event)" onmouseout="clearinfo()">AJAX In Action(AJAX实战)</span></p>
<p><span id="book6" onmouseover="show(this,event)" onmouseout="clearinfo()">AJAX Hacks(AJAX技巧)</span></p>
<div id="divnode" style="position:absolute;">
<table id="mtable" bgcolor="#FFFAFA" border="0" cellspacing="2" cellpadding="2" width="300">
<tbody id="message"></tbody>
</table>
</div>
<script src="xmlhttp.js"></script>
<script type="text/javascript">
var xmlhttp;
var myEvent;
var sNode;
var mouseX;
var mouseY;
function show(spanNode,env){
if(!env){
myEvent = window.event;
} else{
myEvent = env;
}
mouseX = myEvent.clientX;
mouseY = myEvent.clientY;
sNode = spanNode;
xmlhttp = new MyXMLHttpRequest();
xmlhttp.send("POST","ToolTip","id="+spanNode.id,callback);
}
function callback(responseText,responseXML){
clearinfo();
var info = "";
var infoTextNode = responseXML.getElementsByTagName("info")[0].firstChild;
if(infoTextNode){
info = infoTextNode.nodeValue;
}
var divNode = document.getElementById("divnode");
divNode.style.border = "black 1px solid";
var left = mouseX + 5;
var top = mouseY + 5;
divNode.style.left = left + "px";
divNode.style.top = top + "px";
var trNode = document.createElement("tr");
var tdInfoNode = document.createElement("td");
var infoTextNode = document.createTextNode(info);
tdInfoNode.appendChild(infoTextNode);
trNode.appendChild(tdInfoNode);
var tbodyNode = document.getElementById("message");
tbodyNode.appendChild(trNode);
}
function clearinfo(){
var messageNode = document.getElementById("message");
var length = messageNode.childNodes.length;
for (var i = length - 1; i >= 0 ; i--) {
messageNode.removeChild(messageNode.childNodes[i]);
}
var divNode = document.getElementById("divnode");
divNode.style.border = "none";
}
</script>
</body>
</html>
=========================================================================
onkeyup捕获键盘按下的事件,div框的位置,服务器端响应回来的内容存储方式,
高亮显示选中的div框中的信息,按回车后高亮选中的信息回被补到text框里面去,如何
清除div,backspace退格的过程中div框里的信息会根据文本框中的信息的改变而改变
客户端:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
自动完成的示例:
<input type="text" id="autotext" onkeyup="completeText(event)"/>
<div style="position:absolute;" id="tip" >
<table id="tiptable" bgcolor="#FFFAFA" border="0" cellspacing="0" cellpadding="0">
<tbody id="tiptbody"></tbody>
</table>
</div>
<script src="xmlhttp.js"></script>
<script type="text/javascript">
var xmlhttp;
var textNode;
var tipNode;
var tableNode;
var tbodyNode;
var myEvent;
var keyCode;
function completeText(event){
if(!event){
myEvent = window.event;
} else{
myEvent = event;
}
keyCode = myEvent.keyCode;
if((keyCode>=48 && keyCode<=90) || keyCode == 8){
init();
clearTbody();
xmlhttp = new MyXMLHttpRequest();
xmlhttp.send("POST","AutoComplete","text="+textNode.value,callback,fail);
} else if(keyCode == 38 || keyCode == 40){
moveHighLight(keyCode);
} else if(keyCode == 13){
//遍历去找谁是高亮显示的,然后将高亮显示的信息弄到文本框里面去,然后清除
//div提示框
for(var i=0;i<tbodyNode.childNodes.length;i++){
var node = tbodyNode.childNodes[i];
if(node.style.backgroundColor == "red"){
textNode.value = node.firstChild.firstChild.nodeValue;
break;
}
}
clearTbody();
}
}
function init(){
textNode = document.getElementById("autotext");
tipNode = document.getElementById("tip");
tableNode = document.getElementById("tiptable");
tbodyNode = document.getElementById("tiptbody");
}
function callback(responseText,responseXML){
var left = textNode.offsetLeft;//找的是相对于左边的位置
var tmp = textNode.offsetParent;//找的是父层次的位置
while(tmp){//父层次的左边界值也会对真实的边界值有影响
left += tmp.offsetLeft;
tmp = tmp.offsetParent;
}
tipNode.style.left = left + "px";
var top = textNode.offsetTop;
tmp = textNode.offsetParent;
while(tmp){
top += tmp.offsetTop;
tmp = tmp.offsetParent;
}//通过循环直到不存在父层次的时候,这样找到的offsetTop和offsetLeft
//才是真正相对于浏览器的左边界和上边界的位置。
//其实offsetLeft和offsetTop是相对于当前的文本框的父层次来说的。
//所谓层次是div中一层一层的嵌套。
tipNode.style.top = top + textNode.offsetHeight + "px";
//将div提示框的顶边界加上一个文本框的高度值才是真实的顶高度
tableNode.style.width = textNode.offsetWidth + "px";//限制div提示框的宽度
//浏览器的坐标原点在左上角。
clearTbody();
//eval的入口参数应该是一段可以运行的javaScript代码,其实也就是把入口参数运行了一下
//通过下面的方式拿到服务器端得到的数组,便于后面的遍历
var tipArray = eval(responseText);
var tdNode;
var trNode;
//动态生成tr和td的节点
for(var i=0;i<tipArray.length;i++){
tdNode = document.createElement("td");
tdNode.appendChild(document.createTextNode(tipArray[i].value));
tdNode.onmousemove = function(){
this.style.backgroundColor = "red";
};
tdNode.onmouseout = function(){
this.style.backgroundColor = "#FFFAFA";
};
tdNode.onclick = function(){
textNode.value = this.firstChild.nodeValue;
clearTbody();
};
trNode = document.createElement("tr");
trNode.appendChild(tdNode);
tbodyNode.appendChild(trNode);
}
}
function fail(status){
clearTbody();
}
//干掉div提示框。
function clearTbody(){
while(tbodyNode.childNodes.length > 0){
tbodyNode.removeChild(tbodyNode.lastChild);
}
}
//按上下键让选中的地方高亮。
function moveHighLight(keyCode){
if(keyCode == 40){
for(var i=0;i<tbodyNode.childNodes.length;i++){
var node = tbodyNode.childNodes[i];
if(node.style.backgroundColor == "red"){
node.style.backgroundColor = "#FFFAFA";
if(i == tbodyNode.childNodes.length -1){
var focusNode = tbodyNode.childNodes[0];
focusNode.style.backgroundColor = "red";
}else{
var focusNode = tbodyNode.childNodes[i+1];
focusNode.style.backgroundColor = "red";
}
return;
}
}
tbodyNode.firstChild.style.backgroundColor = "red";
}else{
for(var i=0;i<tbodyNode.childNodes.length;i++){
var node = tbodyNode.childNodes[i];
if(node.style.backgroundColor == "red"){
node.style.backgroundColor = "#FFFAFA";
if(i == 0){
var focusNode = tbodyNode.childNodes[tbodyNode.childNodes.length-1];
focusNode.style.backgroundColor = "red";
}else{
var focusNode = tbodyNode.childNodes[i-1];
focusNode.style.backgroundColor = "red";
}
return;
}
}
tbodyNode.lastChild.style.backgroundColor = "red";
}
}
</script>
</body>
</html>
服务器端:
/**
* Created by IntelliJ IDEA.
* User: xingxing
* Date: 2007-3-29
* Time: 22:36:31
* To change this template use File | Settings | File Templates.
*/
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
public class AutoComplete extends javax.servlet.http.HttpServlet {
ArrayList tipList;
public void init(javax.servlet.ServletConfig servletConfig) throws javax.servlet.ServletException{
tipList = new ArrayList();
tipList.add("anyone");
tipList.add("anything");
tipList.add("apple");
tipList.add("abandon");
tipList.add("breach");
tipList.add("break");
tipList.add("boolean");
tipList.add("bad");
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Contorl","no-cache");
PrintWriter out = response.getWriter();
String text = request.getParameter("text");
if(text != null && text.length() > 0){
StringBuffer buffer = new StringBuffer();
buffer.append("[");
for(int i = 0; i < tipList.size(); i++){
String str = (String)tipList.get(i);
if(str.startsWith(text)){
buffer.append("{value:\"").append(str).append("\"},");
}
}
if(buffer.length() > 0){
buffer.delete(buffer.length()-1,buffer.length());
buffer.append("]");
}
if(buffer.length() > 1){
System.out.println(buffer);
out.println(buffer.toString());
} else{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
} else{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
doPost(request,response);
}
}
=========================================================================
WebService是可以提供任何程序通过网络访问的一种服务。
主流用java、C#做WebService,然后不管什么语言按照正确的访问方式都可以访问这个WebService
达到跨平台的特性。
最大的优势是跨平台的可互操作性
SOA(Service-Oriented Architecture)面向服务的架构。
现在如果要做WebService的话,其实大部分工作和以前没有太大的区别,不论是用开源框架
还是用Sun自己的jdk实现方式,都是差不多,唯一需要多做一些的是给你的方法打个标签
比如在前面加上一个“@”之类的东西
如何使用java语言实现一个WebService??
jdk6里面做WebService非常的简单,甚至不需要服务器的支持就可以直接发布WebService
MyEclipse中新建一个Web工程
//注意下面这个包是jdk1.6中的!
import javax.jws.* ;
//给类打标签
@WebService(targetNamespace="http://wang.com")
@SOAPBinding(style=SOAPBinding.Style.RPC)
public class Hello
{
//给方法打标签
@WebMethod
public String sayHello(String name)
{
return "hello " + name ;
}
};
public class Publish
{
public static void main(String[] args)
{
//使用静态方法发布,第一个参数是WebService地址,第二个类是对应的对象。
Endpoint.publish("http://127.0.0.1:8000/Hello",new Hello());
}
}
http://127.0.0.1:8000/Hello?wsdl:可以在浏览器中看到你写的服务的描述语言WSDL
再写一个WebService的客户端程序
命令行中输入:wsimport -keep http://127.0.0.1:8000/Hello?wsdl
就可以在http://wang.com中的倒序包里面,也就是com.wang中生成客户端代码框架了。
public class Client
{
public static void main(String[] args)
{
//生成service代理
HelloService service = new HelloService() ;
Hello hello = service.getHelloPort() ;
System.out.println(hello.sayHello("wangxingkui"));
}
}
最后说一下如何用Ajax访问WebService:
业务数据要序列化为XML,结构是XSD的形式。一个很好的XSD的可视化编辑工具是
XMLSpy