Search box ajax request with input prompt

Drawing first

 

The first files to be referenced are:

base.css  https://www.cnblogs.com/chenyingying0/p/12363689.html

jquery.js 

transition.js  https://www.cnblogs.com/chenyingying0/p/12363649.html

showhide.js  https://www.cnblogs.com/chenyingying0/p/12363707.html

search.js 

(function($){
    "use strict";

    //cache
    var cache={
        data:{},
        count:0,//Number of data bars
        addData:function(data,key){
            if(!this.data[key]){
                this.data[key]=data;
                this.count++;            
            }
        },
        readData:function(key){
            return this.data[key];
        },
        deleteDataByKey:function(key){
            delete this.data[key];
            this.count--;
        },
        deleteDataByNum:function(num){
            var count=0;
            //No object length Property, only through for in To traverse
            for(var p in this.data){
                if(count>=num) break;
                this.deleteDataByKey(p);
                this.count++;
            }
        }

    };

    function Search(elem,options){
        this.elem=elem;//Already passed in jquery object
        this.options=options;

        this.form=this.elem.find(".search-form");
        this.input=this.elem.find(".search-input");
        this.list=this.elem.find(".search-list");

        this.loaded=false;//Is it loaded? html
        
        //Binding submit event, event agent
        this.elem.on("click",".search-btn",$.proxy(this.submit,this));
        //If autocomplete is set
        if(this.options.autocomplete) this.autocomplete();
    }

    //Default parameters
    Search.defaults={
        autocomplete:false,
        url:"https://suggest.taobao.com/sug?code=utf-8&_ksTS=1484204931352_18291&callback=jsonp18292&k=1&area=c2c&bucketid=6&q=",
        css3:false,
        js:false,
        animation:"fade",
        delay:200//Default 200ms delay
    }

    Search.prototype.submit=function(){
        if($.trim(this.input.val())==="") return false;
        this.form.submit();
    }

    Search.prototype.autocomplete=function(){
        var self=this;
        var timer=null;

        this.input.on("input",function(){

            if(self.options.delay){
                clearTimeout(timer);
                timer=setTimeout(function(){
                    self.getData();
                },self.options.delay);                
            }else{
                self.getData();
                //delay When it is 0, the timer does not need to be turned on
                //Because the timer is asynchronous, even if the delay is 0, it will enter the queued state and cannot be executed immediately
            }

        });

        this.list.showHide(this.options);//towards showhide Component parameters, initialization

        //Show hidden dropdown
        this.input.on("focus",$.proxy(this.showList,this))
                  .on("click",function(){
                      return false;//Prevent bubbling when clicking document
                  });
        $(document).on("click",$.proxy(this.hideList,this));
    }

    Search.prototype.getData=function(){
        var self=this;
        var inputVal=this.input.val();

        if(!inputVal) return self.elem.trigger("search-noData");

        //Determine whether there is a cache
        if(cache.readData(inputVal)) return self.elem.trigger("search-getData",[cache.readData(inputVal)]);

        if(this.jqXHR) this.jqXHR.abort();//Conduct ajax When requesting, terminate the previous request first
        this.jqXHR=$.ajax({
            url:this.options.url+encodeURIComponent($.trim(inputVal)),
            dataType:"jsonp"
        }).done(function(data){
            //Send out data Data, triggering events            
            cache.addData(data,inputVal);//Add cache
            console.log(cache.data);
            console.log(cache.count);
            self.elem.trigger("search-getData",[data]);//Data needs to be in array form
        }).fail(function(){
            //Send failure data, trigger event
            self.elem.trigger("search-noData");
        }).always(function(){
            //After execution
            self.jqXHR=null;
        });    
    }

    Search.prototype.showList=function(){
        //list There's something in it
        if(!this.loaded) return;
        this.list.showHide("show");//Use showhide Component show Method
    }

    Search.prototype.hideList=function(){
        this.list.showHide("hide");//Use showhide Component hide Method
    }

    Search.prototype.setInput=function(val){
        this.input.val(val);
    }

    Search.prototype.appendHTML=function(html){
        this.list.html(html);
        this.loaded=!!html;//!!To Boolean, if html If there is content, it will be true; otherwise, it will be false
    }

    //Plug-in form
    $.fn.extend({
        search:function(opt,value){
            return this.each(function(){
                var ui=$(this);
                var search=ui.data("search");
                //opt Is a parameter object
                var options=$.extend({},Search.defaults,ui.data(),typeof opt==="object"&&opt);
                
                //Single example: one DOM Element corresponds to an instance. If it already exists, it does not need to be instantiated repeatedly
                if(!search){
                    search=new Search(ui,options);
                    ui.data("search",search);
                }
                
                //Exposed methods for external calls
                if(typeof search[opt]==="function"){
                    search[opt](value);
                }
            });
        }
    });

})(jQuery)

Next is the html code

    <div id="header-search" class="search fl">
        <! -- because there is no search page of its own, it is set to submit to Taobao during demonstration. Refer to Taobao settings -- >
        <form action="https://s.taobao.com/search" class="search-form">
            <! -- because input is an inline block, it is equivalent to display: inline block
            If you wrap, there will be gaps, which are usually half the size of the default font
            Can write without wrapping, but poor readability
            Add left float to solve -- >
            <! -- set name to submit -- >
            < input type = "text" class = "search input FL" name = "Q" placeholder = "soul gourmet" autocomplete = "off" >
            < input type = "submit" value = "search" class = "search BTN FL" >
        </form>
        <ul class="search-list">
            <!-- <li class="search-item text-ellipsis" title="111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111">111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111</li>
            <li class="search-item text-ellipsis" title="222">222</li>
            <li class="search-item text-ellipsis" title="333">333</li> -->
        </ul>
    </div>

Add point style

    .fl{
        float:left;
    }
    .search{
        margin-top:36px;
        margin-left:144px;
        position: relative;
        width:679px;
        border:1px solid #cfd2d5;
    }
    .search-input{
        width:586px;
        height:40px;
        line-height:40px;
        background-color:#fff;
        border:none;
        padding:0 10px;
    }
    .search-btn{
        width:73px;
        height:40px;
        background-color:#07111b;
        color:#fff;
        line-height:40px;
        text-align: center;
        cursor:pointer;
        border:none;
    }
    .search-list{
        display: none;
        background-color:#fff;
        position: absolute;
        width:606px;
        top:100%;/*Height of parent container*/
        left:-1px;
        border:1px solid #cfd2d5;
    }
    .search-item{
        height:24px;
        line-height:24px;
        padding:0 10px;
    }
    .search-item:hover{
        background-color:#f3f5f7;
        cursor: pointer;
    }

js calling search function

    <script>
//search
    var headerSearch=$("#header-search");
    var html="";
    var maxNum=10;//Maximum display data

    headerSearch.search({
        autocomplete:true,
        css3:false,
        js:false,
        animation:"fade",
        delay:0
    });

    //Receiving events
    headerSearch.on("search-getData",function(e,data){
        //console.log(e.type);
        console.log(data);
        
        var ui=$(this);
        //Processing after data acquisition
        html=createHeaderList(data,maxNum);
        ui.search("appendHTML",html);

        if(html){
            ui.search("showList");
        }else{
            ui.search("hideList");
        }
        
    }).on("search-noData",function(e){

        $(this).search("hideList");//Hide dropdown
        $(this).search("appendHTML","");//Empty content

    }).on("click",".search-item",function(){

        $(this).search("setInput",$(this).text());
        $(this).search("submit");

    });

    //Establish header Drop down list structure of search box in
    function createHeaderList(data,maxNum){
        var html="";
        var dataNum=data["result"].length;//Actual data volume

        if(dataNum===0) return "";

        for(var i=0;i<dataNum;i++){
            if(i>=maxNum) break;
            html+='<li class="search-item text-ellipsis" title="'+data["result"][i][0]+'">'+data["result"][i][0]+'</li>';
        }
        return html;
    }
    </script>

complete

Release the complete page code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>search</title>
    <link rel="stylesheet" href="../css/base.css">
    <link rel="stylesheet" href="../css/search.css">
</head>
<body>
    <div id="header-search" class="search fl">
        <!-- Since there is no search page of its own, it is set to submit to Taobao during demonstration. Refer to Taobao settings -->
        <form action="https://s.taobao.com/search" class="search-form">
            <!-- Because input Is an inline block, equivalent to display:inline-block
            //If you wrap, there will be gaps, which are usually half the size of the default font
            //Can write without wrapping, but poor readability
            //All add left float to solve -->
            <!-- Set up name Submission -->
            <input type="text" class="search-input fl" name="q" placeholder="Soul food" autocomplete="off">
            <input type="submit" value="search" class="search-btn fl">
        </form>
        <ul class="search-list">
            <!-- <li class="search-item text-ellipsis" title="111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111">111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111</li>
            <li class="search-item text-ellipsis" title="222">222</li>
            <li class="search-item text-ellipsis" title="333">333</li> -->
        </ul>
    </div>
    <script src="../js/jquery.js"></script>
    <script src="../js/transition.js"></script>
    <script src="../js/showhide.js"></script>
    <script src="../js/search.js"></script>
    <script>
//search
    var headerSearch=$("#header-search");
    var html="";
    var maxNum=10;//Maximum display data

    headerSearch.search({
        autocomplete:true,
        css3:false,
        js:false,
        animation:"fade",
        delay:0
    });

    //Receiving events
    headerSearch.on("search-getData",function(e,data){
        //console.log(e.type);
        console.log(data);
        
        var ui=$(this);
        //Processing after data acquisition
        html=createHeaderList(data,maxNum);
        ui.search("appendHTML",html);

        if(html){
            ui.search("showList");
        }else{
            ui.search("hideList");
        }
        
    }).on("search-noData",function(e){

        $(this).search("hideList");//Hide drop-down list
        $(this).search("appendHTML","");//Empty content

    }).on("click",".search-item",function(){

        $(this).search("setInput",$(this).text());
        $(this).search("submit");

    });

    //Establish header Drop down list structure of search box in
    function createHeaderList(data,maxNum){
        var html="";
        var dataNum=data["result"].length;//Actual data volume

        if(dataNum===0) return "";

        for(var i=0;i<dataNum;i++){
            if(i>=maxNum) break;
            html+='<li class="search-item text-ellipsis" title="'+data["result"][i][0]+'">'+data["result"][i][0]+'</li>';
        }
        return html;
    }
    </script>
</body>
</html>

Tags: Javascript JQuery css3

Posted on Tue, 25 Feb 2020 09:22:32 -0500 by nekoanz