[easyUI] autocomplete 簡單自動完成以及ajax從服務器端完成

  經過id取input標籤對象,調用autocomplete方法java

<script>
    var sources = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"
          ]; 
    $(function() {
        $( "#tags" ).autocomplete({
            source:sources
        });
    });
</script>
<body>
    <div class="ui-widget">
        <h2>查詢:<input id="tags"></h2>
    </div>
</body>

{source:sources}將多個sources的String類型數組,包裝成JSON.數組

 

Ajax服務器端完成:服務器

服務器端網頁的Java代碼,也只有java代碼.app

    String query = request.getParameter("term");//獲取要匹配的參數
    String[] sources = {"ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"};
    StringBuilder builder = new StringBuilder("[");
    for(int i=0;i<sources.length;i++){//遍歷目標數組,返回符合條件的結果
        if(null != query){
            if(sources[i].indexOf(query) >= 0){//表示若是輸入了query,sources[i]的String包含String query
                builder.append("{\"label\":\""+sources[i]+"\"},");//拼接成{"label":sources[i]}的JSON數據
            }
        }else{//若是不輸入query,返回全部的sources[i]成爲JSON數組.
            builder.append("{\"label\":\""+sources[i]+"\"},");
        }
    }
    String result = builder.toString();//轉換爲字符串.
    if(result.endsWith(",")){//由於拼接的結果轉換成字符串後,數組內會多出","
        result = result.substring(0,result.length()-1);//須要截去最後一個逗號.
    }
    result+="]";//拼接"]"
    out.print(result);
    
View Code

script:jsp

    $(function() {
        $( "#tags" ).autocomplete({
            source:function(request,response){
            //request.term估計是將input內容提交後的字符串."term='字符串'",其實等價於傳入一個
            //{"term":"字符串"}的JSON數據. 具體在jQuery1.11.10的幫助文檔中有所描述,搜get第二個便是.
                $.get("server/demo4_server.jsp","term="+request.term,function(data){
                //url(目標地址),data(傳入數據),callback(回調函數)
                    var result = $.parseJSON(data);
                    response(result);// 輸出返回結果
                });
            }
        });
    });
View Code

parseJSON(String strJSON)函數:ide

相關文章
相關標籤/搜索