本次我们再做一点,给这个搜索栏加入一个能够表示请求状态的功能 先引出Ajax.Responsders对象 这还是一个prototype类库的ajax对象,没有接触的朋友请去找我的ajax入门3
这个对象用于注册Ajax的事件监听器,无论任何一个xmlhttprequest对象与服务器发生交互,该对象注册的监听器都将被自动调用
首先在我们的仿造google搜索栏的项目中的test.js脚本文件中加入一个事件监听器 //定义全局事件处理 var globalMan={ //开始交互时运行 onCreate: function(){ //alert("onCreate()"); Element.show("loading"); }, onFailure: function(){ alert("服务器错误或者网络连接错误"); }, onComplete:function(){ if(Ajax.activeRequestCount == 0){ //alert("onComplete"); Element.hide("loading"); } } }
然后用 Ajax.Responders对象将它绑定 Ajax.Responders.register(globalMan);
其中onCreate为开始交互时,onFailure为交互失败,onComplete为交互完成 Ajax.activeRequestCount 表示 Ajax类下的activeRequestCount属性,这个属性代表了正在进行交互的xmlhttprequest对象的个数,当它为0时,表示所有的局部请求都已完成.
这里我们仅仅对一个id属性为”loading”的div层进行了显示和隐藏的操作,用来提示用户交互是否在执行,如果交互开始执行就显示它,提示用户开始交互了,交互完毕就隐藏它. 下面我们在页面中加入这个loading层
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <script src="js/prototype.js"></script> <script src="js/test.js" ></script> <body> <table width="100%" border="1" bordercolor="#000000"> <tr> <td width="18%"> <input name="text" type="text" id="itext" onKeyUp="getXML()"/> <input name="button" type="button" value="搜索"/> <div id="outdiv" style=" display:none; width:119px; height:20; position:absolute; left: 16px; top: 41px; background-color:#ECEDFF"> <!-- 此处添加行列 --> </div> </td> <td width="82%"><div id="loading" style="position:absolute; display:none">正在加载...</div> </td> </tr> <tr> <td colspan="2"> </td> </tr> </table> </body> </html>
这里唯一需要注意的是div层的定位,关于position:absolute 的属性等我研究明白了跟大家分享 - -
<疯狂的程序员更新到42了,继续期待>
|
|