js搜索框 js仿百度搜索 js下拉框 jQuery.Autocomplete使用


做了一個網站,需要根據文本框的輸入模糊搜索數據庫內容給出提示供用戶選擇,就找到了jQuery.Autocomplete

效果如下圖:

 

該插件托管在github上,具體地址:https://github.com/agarzola/jQueryAutocompletePlugin

官方的英文文檔:http://api.jqueryui.com/autocomplete/

在使用過程中遇到大坑跟大家說一下。

第一個是插件的數據源問題!

如果要使用服務器的數據源需要在調用autocomplete的時候傳入url的參數!

你可以看一下插件的js代碼,它會把搜索的值以q發送到你指定的url

例如:ajaxSearchbyname.html?q=t&limit=10&timestamp=1439967678104

 

第二個問題是服務器提供的數據格式問題!

一般的使用這個插件的人都是需要從服務器獲取數據來展示,而這個插件需要的不是純的json數據,是需要你服務器按照他的規則拼接一下,具體格式是用\n換行符隔開的json,如下面示例所示:

注意:這里的字段是沒有限制的,自己隨便定義,等到調用插件的時候可以自己寫一下處理函數來處理不同字段。

這個示例給提供了三條數據,每一條數據之間是有一個換行符的!

{"user_id":"3","user_name":"test"}\n
{"user_id":"8","user_name":"test1"}\n
{"user_id":"11","user_name":"test4"}

 

給大家提供一下我的具體代碼:

html:

<div class="form-group">
      <label class="col-sm-2 col-md-2 control-label" for="user_name">負責人:</label>
      <div class="col-sm-10 col-md-5">
         <input type="text" class="form-control" id="user_name"
                 value="<?php echo isset($tplData['user_name']) ? $tplData['user_name'] : '' ?>">
         <input type="hidden" name="user_id"
               value="<?php echo isset($tplData['user_id']) ? $tplData['user_id'] : '' ?>">
     </div>
</div>

javascript:

<link href='__PUBLIC__/Common/jquery.autocomplate/jquery.autocomplete.css' rel='stylesheet'>
<script src="__PUBLIC__/Common/jquery.autocomplate/jquery.autocomplete.js"></script>
<script>
    $(function () {
        $("#user_name").focus().autocomplete("<?php echo U('Admin/user/ajaxSearchbyname')?>", {
            formatItem: function (row, i, max) {
                console.log(row);
                var obj = eval("(" + row + ")"); //轉換成js對象
                return obj.user_name;
            },
            formatResult: function (row) {
                console.log(row);
                var obj = eval("(" + row + ")"); //轉換成js對象
                return obj.user_name;
            }
        }).result(function (event, item) {
            $('[name="user_id"]').val(JSON.parse(item).user_id);
        });

        $('#cancel').click(function (e) {
            e.preventDefault();
            window.location.reload();
        });
    });
</script>

PHP代碼基於thinkphp:

/**
     * 返回模糊搜索數據
     */
    public function ajaxSearchbyname() {
        $name = $this->getGet('q', '');
        $page = $this->getGet('page', 1);
        $condition = array();
        if (!empty($name)) {
            $condition['nick_name'] = array('like', "%$name%");
        }
        $userLogic = new userLogic();
        $res = $userLogic->getPageList($condition, $page, 10);
        $resultStrArr = array();
        foreach ($res as $item) {
            array_push($resultStrArr, json_encode(array('user_id' => $item['user_id'], 'user_name' => $item['user_name'])));
        }
        exit(implode("\n", $resultStrArr));
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM