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

        看了好几天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配置集成



"ajaxService" class="com.kevin.myapp.common.ajax.AjaxServiceProcess">

"target">
"com.kevin.myapp.login.bussiness.LoginServiceImpl">
"loginDAO">"loginDAO"/>




"loginService" parent="baseTxProxy">


"loginDAO" parent="baseTxProxy">
"target">
"com.kevin.myapp.login.dao.LoginDAOImpl">
"sessionFactory">
"mySessionFactory" />




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" %>




Login Success













"/login.do" focus="txtUserInput">
"state" value="login"/>
"20" cellpadding="10" border="0">



"green" size="10">welcome, you has login success ! KevinFramework start simple run !


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




封装的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 = "";
      var undeEnd = ""
;
      var selectSpanStart = ";
      var selectSpanEnd =""
;
      
      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+" οnclick='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                    var doc = responseArray[i];
                    
                    selectSpanMid = selectSpanStart+" οnclick='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 =
                                "" + theTextBox.obj .noMatchingDataMessage + "";
                        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";
       }
 
 

你可能感兴趣的:(ajax,function,javascript,bean,autocomplete,firefox,Java,之,Web,应用,Ajax探索)