您的位置:首页 > Web前端 > JavaScript

Ajax应用之输入提示完全实现

2006-05-26 19:23 337 查看
        看了好几天ajax,感觉总是在一些原来的内容上停留,这些天,看了看ajax in action 书中输入提示得内容,觉得很有意思,以前同时写过,不过很简单,没有事件等的支持,这2天根据xml文档固定数据输入提示,修改为根据数据库内容动态更新,并应用buffalo的bulap实现,重写了一个输入提示,并封装了一下!

       封装后,在需要应用输入提示的页面,只需要加入一个简单到只有1行javaScript代码的回调函数 和 一个调用各自页面所需的ajaxService调用即可。

      写之前,看也看不懂,郁闷的很,现在写出来了,感觉至少清晰了些,没有以前对javascript那么恐惧了,不过,个人感觉javascript简单应用还好,复杂一点的就看不懂了,下面说说关于输入提示实现方面的东西。

功能:可实现提示输入,样式和google的相似,可以通过鼠标和上下键控制选择。主要是应用了javaScript回调和其动态的特性对功能进行封装。可以在IE和Firefox下运行。

目前限制:AjaxService输入参数(String) ,返回值 buffalo支持的返回类型 ,其中需要将需要的东西放到code字段;(改进很方便)

封装之后,页面上需要用到的script代码只有下面这些   

function setPro(){
SetProperties(document.loginForm.txtUserInput,
document.loginForm.txtUserValue,
true,true,true,true,"No matching Data",false,null);
}
var END_POINT="<%=request.getContextPath()%>/xmlhttp";
var buffalo = new Buffalo(END_POINT);
function callService(elementSrc){
buffalo.remoteCall("ajaxService.searchUserCode",[elementSrc], listResult);
}


 Spring配置集成

<beans>

<bean id="ajaxService" class="com.kevin.myapp.common.ajax.AjaxServiceProcess"></bean>

<property name="target">
<bean class="com.kevin.myapp.login.bussiness.LoginServiceImpl">
<property name="loginDAO"><ref local="loginDAO"/></property>
</bean>
</property>
</bean>

<bean id="loginService" parent="baseTxProxy">

<bean id="loginDAO" parent="baseTxProxy">
<property name="target">
<bean class="com.kevin.myapp.login.dao.LoginDAOImpl">
<property name="sessionFactory">
<ref bean="mySessionFactory" />
</property>
</bean>
</property>
</bean>
</beans>


AjaxServiceProcess例子
   

public List searchUserCode(String queryCode){
LoginService loginService = (LoginService)KevinApplicationContext.getBean("loginService");
List list = loginService.searchUserCode(queryCode);
return list;
}


 页面的例子

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>

<html>

<head>
<title>Login Success</title>
<script src="<%=request.getContextPath()%>/scripts/buffalo.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/wytest.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/prototype.js"></script>

<script type="text/javascript">
var END_POINT="<%=request.getContextPath()%>/xmlhttp";
var buffalo = new Buffalo(END_POINT);
function callService(elementSrc){
buffalo.remoteCall("ajaxService.searchUserCode",[elementSrc], listResult);
}
function setPro(){
SetProperties(document.loginForm.txtUserInput,
document.loginForm.txtUserValue,
true,true,true,true,"No matching Data",false,null);
}

</script>

<!--  *************************************     -->

<style type="text/css">
/* Listing 10.5--> */
span.spanTextDropdown{
position: absolute;
top: 0px;
left: 0px;
width: 150px;
z-index: 101;
background-color: #C0C0C0;
border: 1px solid #000000;
padding-left: 2px;
overflow: visible;
display: none;
}

span.spanMatchText{ text-decoration: underline;
font-weight: bold; }
span.spanNormalElement{ background: #C0C0C0; }
span.spanHighElement{ background: #000040;
color: white;
cursor: pointer; }
span.noMatchData{ font-weight: bold;
color: #0000FF; }
</style>
</head>

<body>

<html:form action="/login.do" focus="txtUserInput">
<html:hidden property="state" value="login"/>
<table cellspacing="20" cellpadding="10" border="0">
<tr>
<td><FONT color="green" size="10"><B>welcome, you has login success ! KevinFramework start simple run !</B></FONT></td>
</tr>
</table>

AutoComplete Text Box: <input type="text"  id="txtUserInput" name="txtUserInput" />
<input type="hidden" name="txtUserValue" ID="hidden1" />
<input type="text" name="txtIgnore" style="display:none"/>

</html:form>

</body>
</html>

封装的wytest.js如下所示:
 //default ajax service
//var END_POINT="<%=request.getContextPath()%>/xmlhttp";
//var buffalo = new Buffalo(END_POINT);
var getArrayLength = 0;
var tempResultArray;

window.onload = function(){
        var elemSpan = document.createElement("span");
        elemSpan.id = "spanOutput";
        elemSpan.className = "spanTextDropdown";
        document.body.appendChild(elemSpan);
        
        //Listing 10.7
        document.loginForm.txtUserInput.obj = setPro();
          //SetProperties(document.loginForm.txtUserInput,
            //document.loginForm.txtUserValue,//'typeAheadXML.js',
            //true,true,true,true,"No matching Data",false,null);
      }
      
function SetElementPosition(theTextBoxInt){
        //alert("***********");
        var selectedPosX = 0;
        var selectedPosY = 0;
        var theElement = theTextBoxInt;
        if (!theElement) return;
        var theElemHeight = theElement.offsetHeight;
        var theElemWidth = theElement.offsetWidth;
        while(theElement != null){
          selectedPosX += theElement.offsetLeft;
          selectedPosY += theElement.offsetTop;
          theElement = theElement.offsetParent;
        }
        xPosElement = document.getElementById("spanOutput");
        xPosElement.style.left = selectedPosX;
        xPosElement.style.width = theElemWidth;
        xPosElement.style.top = selectedPosY + theElemHeight
        xPosElement.style.display = "block";
}     
      
      
//set properties
    function SetProperties(xElem,xHidden,//xserverCode,
        xignoreCase,xmatchAnywhere,xmatchTextBoxWidth,
        xshowNoMatchMessage,xnoMatchingDataMessage,xuseTimeout,
        xtheVisibleTime){
          var props={
            elem: xElem,
            hidden: xHidden,
            //serverCode: xserverCode,
            regExFlags: ( (xignoreCase) ? "i" : "" ),
            regExAny: ( (xmatchAnywhere) ? "" : "^" ),
            matchAnywhere: xmatchAnywhere,
            matchTextBoxWidth: xmatchTextBoxWidth,
            theVisibleTime: xtheVisibleTime,
            showNoMatchMessage: xshowNoMatchMessage,
            noMatchingDataMessage: xnoMatchingDataMessage,
            useTimeout: xuseTimeout
          };
          AddHandler(xElem);
          return props;
      }
      
//add handler
    var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!= -1);
      function AddHandler(objText){
        //alert("00000000000000");
        objText.onkeyup = GiveOptions;
        //objText.onblur = function(){
        //  if(this.obj.useTimeout)StartTimeout();
        //}
        if(isOpera)objText.onkeypress = GiveOptions;
      }      
      
      
      var theTextBox;
      var elementSrc = '';
      var arrOptions = new Array();
      var strLastValue = "";
      var bMadeRequest;
      var objLastActive;
      var currentValueSelected = -1;
      var bNoResults = false;
      var isTiming = false;
      var undeStart = "<span class='spanMatchText'>";
      var undeEnd = "</span>";
      var selectSpanStart = "<span style='width:100%;display:block;' class='spanNormalElement' onmouseover='SetHighColor(this)' ";
      var selectSpanEnd ="</span>";
      
      function GiveOptions(e){
           var intKey = -1;
           if(window.event){
              intKey = event.keyCode;
              theTextBox = event.srcElement;
              elementSrc = theTextBox.value;
              //alert("test----"+theTextBox.value);
              
              //add for position
              SetElementPosition(theTextBox);
           }
           else{
              //alert("test----"+theTextBox.value);
              intKey = e.which;
              theTextBox = e.target;
              elementSrc = theTextBox.value;
              SetElementPosition(theTextBox);
           }
           if(theTextBox.value.length == 0 && !isOpera){
              //alert("length= "+theTextBox.value.length);
              arrOptions = new Array();
              HideTheBox();
              strLastValue = "";
              objLastActive = "";
              return false;
           }
           if(objLastActive == theTextBox){
              if(intKey == 13){
                    GrabHighlighted();
                    theTextBox.blur();
                    return false;
                  }
                  else if(intKey == 38){
                    MoveHighlight(-1);
                    return false;
                  }
                  else if(intKey == 40){
                    MoveHighlight(1);
                    return false;
                  }
                  else{}
            }
            if(objLastActive != theTextBox ||
               theTextBox.value.indexOf(strLastValue) != 0 ||
              //((arrOptions.length==0 || arrOptions.length==15 ) && !bNoResults) ||
               (theTextBox.value.length <= strLastValue.length)){
                 objLastActive = theTextBox;
                 //BuildList(theTextBox.value);
            }
            
            strLastValue = theTextBox.value;
            //alert("elementSrc= "+elementSrc);
            if (elementSrc != '')
                callService(elementSrc);
                //buffalo.remoteCall("ajaxService.searchUserCode",[elementSrc], listResult);
        }
        
        var flag = false;
        function listResult(reply) {
            //alert("reply="+reply);
            var ct =document.getElementById("spanOutput");
            //alert("ct= "+ct.className);
            if(flag){
                //var len = ct.rows.length ;
                //for( var i = 0 ; i < len; i ++ ){
                //    ct.deleteRow();
                //}
            }
            flag = true;
            
            var theMatches = '';
            var responseArray = reply.getResult();
            
            //add for firefox
            tempResultArray = responseArray;
            
            getArrayLength = responseArray.length;
            if (responseArray.length == 0) {
                
                selectSpanMid = selectSpanStart+" onclick='SetText(" + 0 + ")'" +
                      " id='OptionsList_" +
                      0 + "' theArrayNumber='"+ 0 +"' " +"code='No Result"+ "'>";
                selectSpanValue = undeStart+"No Result"+undeEnd+undeEnd;
                theMatches += selectSpanMid + selectSpanValue ;
                
            } else {  
                for (var i=0;i<responseArray.length;i++) {
                    var doc = responseArray[i];
                    
                    selectSpanMid = selectSpanStart+" onclick='SetTextOnClick(" + i + ")'" +
                      " id='OptionsList_" +
                      i + "' theArrayNumber='"+ i +"' " +"code='"+ doc.code +"'>";
                    selectSpanValue = undeStart+doc.code+undeEnd+undeEnd;
                    theMatches += selectSpanMid + selectSpanValue ;
                }
                
              }
              
              if(theMatches.length > 0){
                    //alert("theMatches="+theMatches);
                    document.getElementById("spanOutput").innerHTML = theMatches;
                    document.getElementById("OptionsList_0").className="spanHighElement";
                    currentValueSelected = 0;
                    bNoResults = false;
                }
                  else{
                          currentValueSelected = -1;
                        bNoResults = true;
                        if(theTextBox.obj.showNoMatchMessage)
                            document.getElementById("spanOutput").innerHTML =
                                "<span class='noMatchData'>" + theTextBox.obj .noMatchingDataMessage + "</span>";
                        else HideTheBox();
                  }
              
              ShowSpan("spanOutput");
            }
            
        
        
        //hide box spanOutput
        function HideTheBox(){
            document.getElementById("spanOutput").style.display = "none";
            currentValueSelected = -1;
            //EraseTimeout();
        }
        
        //selected element
        function GrabHighlighted(){
            if(currentValueSelected >= 0){
                  //xVal is the value of array[i]
                  var xVal = document.getElementById("OptionsList_" +
                              currentValueSelected);
                  //alert("currentValueSelected= "+currentValueSelected);
                              
                  //alert("xVal= "+xVal.code);            
                              
                  SetText(xVal);
                  HideTheBox();
            }
        }
        
        function SetText(xVal){
        
            var value = tempResultArray[currentValueSelected];
            //alert(value.code);
            //add for firefox
            theTextBox.value = value.code ;//set text value
        
            //theTextBox.value = xVal.code; //set text value
            //alert("theTextBox.value= "+theTextBox.value);
            //theTextBox.obj.hidden.value = arrOptions[xVal][1];
            document.getElementById("spanOutput").style.display = "none";
            currentValueSelected = -1; //remove the selected index
        }
        
        function SetTextOnClick(elem){
            var xVal = document.getElementById("OptionsList_" +
                              currentValueSelected);
            //alert("OptionsList= " +"OptionsList_"+currentValueSelected);
            //alert("xVal= "+xVal+"   xVal.code= "+xVal.code);
            SetText(xVal);  
            HideTheBox();                
        }
        
        function MoveHighlight(xDir){
            if(currentValueSelected >= 0){
                  newValue = parseInt(currentValueSelected) + parseInt(xDir);
                  if(newValue > -1 && newValue < getArrayLength){
                        currentValueSelected = newValue;
                        SetHighColor (null);
                  }
            }
       }
       
       function SetHighColor(theTextBox){
            if(theTextBox){
              currentValueSelected =
              theTextBox.id.slice(theTextBox.id.indexOf("_")+1,
              theTextBox.id.length);
            }
            for(i = 0; i < getArrayLength; i++){
              document.getElementById('OptionsList_' + i).className =
                'spanNormalElement';
            }
            document.getElementById('OptionsList_' +
              currentValueSelected).className = 'spanHighElement';
      }
      
      
      function ShowSpan(divid){
            var xPosElement = document.getElementById(divid);
            xPosElement.style.display = "block";
       }

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息