JQuery + ajax 유사 바 이 두 검색 자동 일치 기능 구현

18787 단어 jsjqueryAjax코드
프론트 코드
   <tr margin-left:40px>
                <td style="margin-left:40px;font-size:14px">    :</td>
                <td style="width:300px">
                    <input type="text" value="       " id="companyName" onblur="QueryCompanyInfo(this)" onchange="QueryIllegalCompany()" onfocus=" if (this.value == this.defaultValue) this.value = ''" class="easyui-validatebox" required="true" missingmessage="        " size="10" type="text" />
                </td>

            </tr>
            @*           input*@
            <input id="urllink" type="hidden" value="/BidTRecordManager/QueryIllegalCompany" />
            @*                *@
            <div id="auto" style="z-index:4; position: absolute; display: none; border: 1px solid #95b8e7; background-color:#fff"></div>

js 코드
//          queryCondition
function addEvent(obj, type, fn) {
    if (obj.addEventListener) {//     
        obj.addEventListener(type, fn, false);
    } else if (obj.attachEvent) {//ie   
        obj.attachEvent("on" + type, fn);
    }
}



addEvent(window, "load", function () {

    var input = document.getElementById("companyName");
    
    addEvent(input, "keyup", function (event, input, urllink) {
        var xmlHttp;
        var params;
        var strLike;
        var input = document.getElementById("companyName");
        var keycode = AutoComplete.prototype.isIE() ? window.event.keyCode : event.which;//e.which        

        if (typeof XMLHttpRequest != 'undefined') {//     
            xmlHttp = new XMLHttpRequest();

        } else if (typeof ActiveXObject != 'undefined') { //IE   
            var version = [
                'MSXML2.XMLHttp.6.0',
                'MSXML2.XMLHttp.3.0',
                'MSXML2.XMLHttp'
            ];
            for (var i = 0; i < versions.length; i++) {
                try {
                    xmlHttp = new ActiveXObject(version[i]);
                } catch (e) {
                    //  
                }
            }
        } else {
            throw new Error('        XHR  !');

        }

        //      url     
        strLike = document.getElementById("companyName").value;
        //var url = "queryTestHandler.ashx?strLike=" + strLike + new Date().getTime();
        var urllink = document.getElementById("urllink").value;

        var url = urllink + "?strLike=" + strLike + "&t=" + new Date().getTime();
        xmlHttp.open("get", url, true);//get    
        xmlHttp.setRequestHeader("Content-Type", "text/xml");//       
        xmlHttp.send(null);

        xmlHttp.onreadystatechange = callback;
        function callback() {

            if (xmlHttp.readyState == 4) {

                //              
                if (xmlHttp.status == 200) {

                    //            200,        
                    //           
                    params = xmlHttp.responseText;
                    if ((keycode >= 37 && keycode <= 40) || keycode == 13) {
                        if (autoComplete != null && (keycode == 38 || keycode == 40 || keycode == 13)) {
                            autoComplete.setStyle(keycode);
                        }
                    }
                    else {

                        autoComplete = new AutoComplete(params, input);
                        autoComplete.show();
                    }
                }
            }

        }//callback End

    })
 })

//                 
setTimeout(function AutoSuggest(input, event, urllink) {
    var xmlHttp;
    var params;
    var strLike;
    //alert();
    //alert(input);
    //alert(urllink);
    //alert(input.value);
    var keycode = AutoComplete.prototype.isIE() ? window.event.keyCode : event.which;//e.which        
    //alert();
    if (typeof XMLHttpRequest != 'undefined') {//     
        xmlHttp = new XMLHttpRequest();

    } else if (typeof ActiveXObject != 'undefined') { //IE   
        var version = [
            'MSXML2.XMLHttp.6.0',
            'MSXML2.XMLHttp.3.0',
            'MSXML2.XMLHttp'
        ];
        for (var i = 0; i < versions.length; i++) {
            try {
                xmlHttp = new ActiveXObject(version[i]);
            } catch (e) {
                //  
            }
        }
    } else {
        throw new Error('        XHR  !');

    }

    //      url     
    //strLike = document.getElementById("queryCondition").value;
    //var url = "queryTestHandler.ashx?strLike=" + strLike + new Date().getTime();
    // var urllink = document.getElementById("urllink").value;
    strLike = input.value;
    //alert(strLike);
    var url = urllink + "?strLike=" + strLike + "&t=" + new Date().getTime();
    xmlHttp.open("get", url, true);//get    
    xmlHttp.setRequestHeader("Content-Type", "text/xml");//       
    xmlHttp.send(null);

    xmlHttp.onreadystatechange = callback;
    function callback() {

        if (xmlHttp.readyState == 4) {

            //              
            if (xmlHttp.status == 200) {

                //            200,        
                //           
                params = xmlHttp.responseText;
                if ((keycode >= 37 && keycode <= 40) || keycode == 13) {
                    if (autoComplete != null && (keycode == 38 || keycode == 40 || keycode == 13)) {
                        autoComplete.setStyle(keycode);
                    }
                }
                else {

                    autoComplete = new AutoComplete(params, input);
                    autoComplete.show();
                }
            }
        }

    }//callback End
}, 100);

//AutoComplete Object
var autoComplete = null;

//AutoComplete constructor
function AutoComplete(params, input){
    this.params = params//     ,                   
    this.input = input;//Input    
    this.messages = new Array();//                   ,messages      
    this.message = input.value;//            
    this.inputValue = "";//         ,        ??????????????
    this.size = 0;//         ,  
    this.index = 0;//         
    this.likemsgs = new Array();//          ,    ,         
    //this.likemsgs = this.unique(this.likemsgs);
    this.div = this.$$$('auto');//  $$$  getElementById,        
    this.divInnerHTML = this.div.innerHTML;//        
    this.input.onblur = function(){
        autoComplete.lostFocus();
    }
}

//keyup         ,params           ,input     ,e keyup  


//            
AutoComplete.prototype.strToArray = function(){
    this.messages = this.params.split(",");
}

//       
AutoComplete.prototype.show = function(){
    if (this.message != '') {
        this.inputValue = this.input.value;
        this.strToArray();
        this.emptyDiv();
        this.getLikeMegs();
        this.setDivAttr();
        this.addMessageToDiv();
    }
    else {
        this.emptyDiv();
    }
}

//Style set of information
AutoComplete.prototype.setStyle = function(keycode){
    if (this.size > 0) {
        if (keycode == 38) {//Up  
            this.setStyleUp();
        }
        else 
            if (keycode == 40) { //Down  
                this.setStyleDown();
            }
            else 
                if (keycode == 13) {//Enter
                    
                   
                   this.textToInput(this.$$$(this.index).innerText);
                    
                    
                }
    }
}

//    ,        ,      
//???????????????????????        
AutoComplete.prototype.setStyleUp = function(){
    if (this.index == 0) {//           0,          
        this.index = this.size;//                
        this.$$$(this.index).style.backgroundColor = '#E2EAFF';//      
        this.input.value = this.$$$(this.index).innerText;
    }
    else 
        if (this.index == 1) {
            this.$$$(this.index).style.backgroundColor = '#FFFFFF';//     
            this.input.value = this.inputValue;
            this.index = 0;
            this.input.focus();
        }
        else {
            this.index--;
            this.setOtherStyle();
            this.$$$(this.index).style.backgroundColor = '#E2EAFF';
            this.input.value = this.$$$(this.index).innerText;
        }
}

//  down ,    ,           
AutoComplete.prototype.setStyleDown = function(){
    if (this.index == this.size) {
        this.$$$(this.index).style.backgroundColor = '#FFFFFF';
        this.input.value = this.inputValue;
        this.index = 0;
        this.input.focus();
    }
    else {
        this.index++;//    ,       
        this.setOtherStyle();
        this.$$$(this.index).style.backgroundColor = '#E2EAFF';
        this.input.value = this.$$$(this.index).innerText;
    }
}

//                
AutoComplete.prototype.setOtherStyle = function(){
    for (var i = 1; i <= this.size; i++) {
        if (this.index != i) {
            this.$$$(i).style.backgroundColor = '#FFFFFF';
        }
    }
}

//         ,        
window.onresize = function(){
    if (autoComplete != null) {
        autoComplete.setDivAttr();
    }
}

//              ,       ,        ,      ,        --  //firefox
window.onclick = function(e){
    if (AutoComplete.prototype.$$$('auto').style.display != 'none') {
        var x = e.clientX, y = e.clientY;
        var left = autoComplete.calcOffsetLeft(autoComplete.input);
        var right = autoComplete.calcOffsetLeft(autoComplete.input) + autoComplete.input.offsetWidth;
        var top = autoComplete.calcOffsetTop(autoComplete.input);
        var bottom = autoComplete.input.offsetHeight + autoComplete.calcOffsetTop(autoComplete.input) + autoComplete.div.offsetHeight;
        if (x < left || x > right || y < top || y > bottom) {
            autoComplete.emptyDiv();//                  ,       
        }
    }
}

//        
AutoComplete.prototype.mouseover = function(li){
    li.style.backgroundColor = '#E2EAFF';//   
    this.index = li.id;//     ,                 
    this.setOtherStyle();
}

//        ,          
AutoComplete.prototype.setDivAttr = function(){
    if (this.input != null) {
        this.div.style.width = this.input.offsetWidth + 'px';//           
        this.div.style.left = this.calcOffsetLeft(this.input) + 'px';//          
        this.div.style.top = (this.input.offsetHeight + this.calcOffsetTop(this.input)) + 'px';//               +      
        this.div.style.display = 'block';//            
    }
}

//         ,messages            
//AutoComplete.prototype.getLikeMegs = function(){
//    var j = 0;
//    for (var i = 0; i < this.messages.length; i++) {
//        if ((this.messages[i].length >= this.message.length) && ((this.messages[i].substring(0, this.message.length)) == this.message)) {
//            this.likemsgs[j++] = this.messages[i];
//        }
//    }
//}
//AutoComplete.prototype.unique= function(arr) {
//    var result = [], hash = {};
//    for (var i = 0, elem; (elem = arr[i]) != null; i++) {
//        if (!hash[elem]) {
//            result.push(elem);
//            hash[elem] = true;
//        }
//    }
//    return result;
//}

//AutoComplete.prototype.unique = function (arr) {
//    //alert(arr);
//    var result = [], isRepeated;
//    for (var i = 0, len = arr.length; i < len; i++) {
//        isRepeated = false;//   
//        for (var j = 0, len = result.length; j < len; j++) {
//            if (arr[i] == result[j]) {
//                isRepeated = true;//  
//                continue;
//            }
           
//        }
//        if (!isRepeated) {
//            result.push(arr[i]);
//        }
       
//    }
//    return result;
//}
//      
AutoComplete.prototype.unique = function (someArray) {
    //alert(someArray);
    tempArray = someArray.slice(0);//         
    for (var i = 0; i < tempArray.length; i++) {
        for (var j = i + 1; j < tempArray.length;) {
            //                    
            if (tempArray[j].replace(/(^\s+)|(\s+$)/g, "") == tempArray[i].replace(/(^\s+)|(\s+$)/g, ""))
                //             ,      ;
                //   ,          ,    j   
            {
                tempArray.splice(j, 1);
            }
            else {
                j++;
            }
            //  ,     
        }
    }
    return tempArray;
}

AutoComplete.prototype.getLikeMegs = function () {
   var j = 0;
    for (var i = 0; i < this.messages.length; i++) {
        if ((this.messages[i].length >= this.message.length)) {
            for (var k = 0; k < this.messages[i].length; k++) {
                if (this.messages[i].substring(k, k+this.message.length) == this.message ) {
                    //      
                    this.likemsgs[j++] = this.messages[i];
                }
            }
        }  
    }
    this.likemsgs = this.unique(this.likemsgs);
}
//                   
AutoComplete.prototype.addMessageToDiv = function(){
    var complete = this;
    for (var i = 0; i < this.likemsgs.length; i++) {
        var li = document.createElement('li');//        
        li.id = i + 1;
        li.style.fontSize = '12px';
        li.style.listStyleType = 'none';
        li.style.listStylePosition = 'outside';//   Li  
        li.onmouseover = function(){//        
            complete.mouseover(this);
        }
        li.onmouseout = function(){//        
            this.style.backgroundColor = '#FFFFFF';//     
        }
        li.onclick = function(){//     ,          
            complete.textToInput(this.innerText);
        }
        li.appendChild(document.createTextNode(this.likemsgs[i]));//            ,    li    
        this.div.appendChild(li);//           
        this.divInnerHTML = this.div.innerHTML;
        this.size++;
    }
    if (this.size == 0) {//       ,size=0    
        this.div.innerHTML = "<li style=\"list-style: none outside;font-size:12px;color:red;\">         !</li>";
        this.divInnerHTML = this.div.innerHTML;
    }
}

//       ,             ,           
AutoComplete.prototype.textToInput = function(value){
    this.input.value = value;
    this.emptyDiv();
}

//         
AutoComplete.prototype.emptyDiv = function(){
    this.divInnerHTML = '';
    this.div.innerHTML = this.divInnerHTML;
    this.div.style.display = 'none';
    this.size = 0;
    this.index = 0;
}

//                 
AutoComplete.prototype.calcOffsetLeft = function(field){
    return this.calcOffset(field, 'offsetLeft');
}

//                  
AutoComplete.prototype.calcOffsetTop = function(field){
    return this.calcOffset(field, 'offsetTop');
}

//             ,                    
AutoComplete.prototype.calcOffset = function(field, attr){
    var offset = 0;
    while (field) {
        offset += field[attr];
        field = field.offsetParent;
    }
    return offset;
}

//         IE   ,     
AutoComplete.prototype.lostFocus = function(){
    var active = document.activeElement;
    if (AutoComplete.prototype.isIE() && active != null && active.id != 'auto') {
        this.emptyDiv()
    }
}

//Use $$$ replace getElementById
AutoComplete.prototype.$$$ = function(obj){
    return document.getElementById(obj);
}

//        IE   
AutoComplete.prototype.isIE = function(){
    return window.navigator.userAgent.indexOf('MSIE') != -1;
}

//Firefox innerText define
if (!AutoComplete.prototype.isIE()) {
    HTMLElement.prototype.__defineGetter__("innerText", function(){
        var anyString = "";
        var childS = this.childNodes;
        for (var i = 0; i < childS.length; i++) {
            if (childS[i].nodeType == 1) //    
                anyString += childS[i].innerText;
            else 
                if (childS[i].nodeType == 3) //    
                    anyString += childS[i].nodeValue;
        }
        return anyString;
    });
    HTMLElement.prototype.__defineSetter__("innerText", function(sText){
        this.textContent = sText;
    });
}

배경 코드:
    #region                 
        public ActionResult QueryIllegalCompany()
            
       {
            //           
           string CompanyName = Request["strLike"];
            //                  ,    list
            List<BlackListViewModel> IllegalCompany = iBlackListManagerWCF.QueryIllegalCompany(CompanyName);

            
            string[] results = { "CompanyName" };
            //            
            string s = FuzzyQuery.GetLikeStr<BlackListViewModel>(IllegalCompany, results).ToString();

            return Content(s);


        }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ITOO.EvaluationUI
{
    public static class FuzzyQuery
    {
        /// <summary>
        ///       
        /// </summary>
        /// <typeparam name="T">  </typeparam>
        /// <param name="listObject">      list</param>
        /// <param name="results">     ,              </param>
        /// <returns>      </returns>
        public static StringBuilder GetLikeStr<T>(List<T> listObject, string[] results)
        {
            StringBuilder sb = new StringBuilder();  //           
            if (listObject.Count != 0)
            {

                for (int i = 0; i < listObject.Count; i++)
                {
                    //var item = listObject.ElementAt(i);   //      
                    var item = listObject[i];

                    for (int j = 0; j < results.Length; j++)
                    {
                        System.Reflection.PropertyInfo pi = item.GetType().GetProperty(results[j]);
                        string queryCondition = pi.GetValue(item, null).ToString();
                        sb.Append(queryCondition).Append(",");
                    }
                }

                sb.Remove(sb.Length - 1, 1);

            }
            return sb;

        }

    }
}

좋은 웹페이지 즐겨찾기