DIV CSS 佈局教程網

jQuery autoComplete 外掛:兩種資料來源模式與動態參數傳遞技巧
編輯:JQuery入門技巧     

autoComplete 是 jQuery 時代的經典自動完成外掛。實務上有兩種常見用法:一次載入全部候選資料在本機比對,或每次輸入都請後端即時查詢。本文示範這兩種模式,並說明如何突破它只支援 q / limit 兩個參數的限制。

模式一:一次載入,重複使用

適合候選資料量有限、變動不频繁的情境,例如客戶清單。

前端

/* 客戶名稱自動匹配 */
function customerAutoComplete(){
    $.ajax({
        type: "GET",
        url: encodeURI("/approvalajax/salesOrderApproval_findCustomerList"),
        dataType: "json",
        success: function(data, textStatus){
            if (data != null && data.customerList != null){
                $("#customerFullName").autocomplete(data.customerList, {
                    /** 自訂表頭 **/
                    tableHead: "<div><span class='col-1'>客戶編碼</span>"
                             + "<span class='col-2'>客戶名稱</span></div>",
                    minChars: 0,
                    width: 310,
                    matchContains: "true",
                    autoFill: false,
                    extraParams: { ledger: $("#ledger").val() },
                    formatItem: function(row, i, max) {
                        return "<span class='col-1'>" + row.cusCode + "</span> "
                             + "<span class='col-2'>" + row.cusName + "</span>";
                    },
                    formatMatch: function(row, i, max) { return row.cusCode + row.cusName; },
                    formatResult: function(row) { return row.cusName; }
                }).result(function(e, data, value, sec){
                    /** 選中後的回呼 **/
                    clearCustomerInfo();
                    $("#customerShortName").val(data.cusAbbName);
                    $("#customerFullName").val(data.cusName);
                    $("#customerCode").val(data.cusCode);
                    setPLAndPCAndCP(data.cusCode);        // 依客戶與帳套載入產品線等
                    setInventoryAutoComplete(data.cusCode); // 載入存貨編碼
                }).bind("unmatch", function(){ clearCustomerInfo(); });
            }
        }
    });
}

後端

/** 異步請求結果 */
private Map<String, Object> ajaxResultMap;

/**
 * @Description 依帳套異步加載客戶列表
 */
public String findCustomerList() throws Exception {
    ajaxResultMap = new HashMap<String, Object>();
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    List<ErpCustomer> list = erpDataService.findCustomerList(ledger);
    ajaxResultMap.put("customerList", list);
    return SUCCESS;
}

Struts 設定

<package name="approval-ajax" extends="json-default" namespace="/approvalajax">
  <action name="salesOrderApproval_*" method="{1}" class="xx.xxx.xxAction">
    <result type="json">
      <param name="root">ajaxResultMap</param>
      <param name="contentType">text/html</param>
    </result>
  </action>
</package>

模式二:依輸入內容動態載入

把 URL 直接傳給 autocomplete,外掛會自動在你輸入時發請求,並附上 q 參數。

前端

/* 客戶名稱自動匹配 */
function customerAutoComplete(){
    $("#customerFullName").autocomplete(
        encodeURI("/approvalajax/salesOrderApproval_findCustomerList"), {
        tableHead: "<div><span class='col-1'>客戶編碼</span>"
                 + "<span class='col-2'>客戶名稱</span></div>",
        minChars: 0,
        width: 310,
        matchContains: "true",
        autoFill: false,
        extraParams: { ledger: $("#ledger").val() },
        dataType: 'json',
        parse: function(data) {
            var rows = [];
            if (data == null || data.customerList == null) { return rows; }
            for (var i = 0; i < data.customerList.length; i++){
                rows[rows.length] = {
                    data:   data.customerList[i],
                    value:  data.customerList[i].cusName,
                    result: data.customerList[i].cusName
                };
            }
            return rows;
        },
        formatItem:   function(row, i, max) { /* 同上 */ },
        formatMatch:  function(row, i, max) { return row.cusCode + row.cusName; },
        formatResult: function(row) { return row.cusName; }
    }).result(function(e, data, value, sec){
        clearCustomerInfo();
        $("#customerShortName").val(data.cusAbbName);
        $("#customerFullName").val(data.cusName);
        $("#customerCode").val(data.cusCode);
        $("#licensecode").val(data.licensecode);
        setPLAndPCAndCP(data.cusCode);
        addInventoryAutoComplete($("#detailListTbody").find("input[tdTag=inventoryCode]"));
    }).bind("unmatch", function(){ clearCustomerInfo(); });
}

後端

/** 自動填充輔助字元 */
private String q;

private Map<String, Object> ajaxResultMap;

public String findCustomerList() throws Exception {
    ajaxResultMap = new HashMap<String, Object>();
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    // 外掛會自動把輸入內容放在 q 參數中
    List<ErpCustomer> list = erpDataService.findTop5CustomerList(ledger, q);
    ajaxResultMap.put("customerList", list);
    return SUCCESS;
}

注意:這個外掛預設以 /n 拆分行、| 拆分欄位。若要直接解析 JSON,必須自行實作 parse 方法,否則會跳錯誤。

主要參數速查

  • minChars:觸發前至少輸入的字元數,預設 1;設為 0 時雙擊輸入框或清空內容都會顯示列表。
  • width:下拉寬度,預設等於 input 寬度。
  • max:下拉顯示筆數,預設 10。
  • delay:按鍵後觸發的延遲毫秒數,遠端預設 400、本機 10。
  • autoFill:是否自動把滑鼠所在值填入輸入框,預設 false。
  • mustMatch:為 true 時只允許清單內的值,輸入非法內容不會出現下拉。
  • matchContains:是否在字串內部比對(如 ba 是否匹配 foo bar),用快取時很重要,勿與 autoFill 混用。
  • selectFirst:按 Tab 或 Enter 時是否自動選中第一項,預設 true。
  • cacheLength:結果快取筆數,設 1 為不快取,預設 10。
  • matchSubset:是否使用伺服器查詢快取以減輕負擔,僅在 cacheLength 大於 1 時有效。
  • matchCase:是否區分大小寫。
  • multiple / multipleSeparator:是否允許多值輸入與其分隔符(預設逗號)。
  • scroll / scrollHeight:結果過多時是否出現捲軸及其高度,預設 180px。
  • formatItem / formatResult / formatMatch:分別格式化下拉顯示、寫回輸入框、以及比對時使用的字串。
  • extraParams:額外送給後端的參數,鍵值對形式。

選中項目後可用 result 事件做後續處理:

$("#singleBirdRemote").result(function(event, data, formatted) {
    // 選取後給其他控制項賦值、觸發其他事件等
});

進階:讓 extraParams 變「活」的

外掛只認 q 與 limit 兩個參數,作者另外提供了 extraParams 作為擴充。問題是 extraParams 是初始化時就固定的靜態值。舉例來說,公司名稱自動完成需要同時帶上「城市」參數,而城市是使用者事後才選的,這時 extraParams 就力不從心。

解法是在外掛的 onChange 流程中插入一個自訂回呼,讓每次觸發前都能重算 options。改動只有三步。

步驟一:在 defaults 增加 onBegin

找到 $.Autocompleter.defaults = ... 附近,補上一行:

onBegin: null,

步驟二:在 onChange 開頭呼叫它

找到 function onChange(crap, skipPrevCheck),在函式最前面插入:

function onChange(crap, skipPrevCheck) {
    // 啟動 onChange 時,允許重新設定 options
    if (options.onBegin) {
        var op = options.onBegin(options);
        if (op) {
            $.extend(options, op);
        }
    }

    if (lastKeyPressCode == KEY.DEL) { select.hide(); return; }

    var currentValue = $input.val();
    if (!skipPrevCheck && currentValue == previousValue) return;
    previousValue = currentValue;
    currentValue = lastWord(currentValue);

    if (currentValue.length >= options.minChars) {
        $input.addClass(options.loadingClass);
        if (!options.matchCase) currentValue = currentValue.toLowerCase();
        request(currentValue, receiveData, hideResultsNow);
    } else {
        stopLoading();
        select.hide();
    }
}

步驟三:呼叫時挂上 onBegin

/* 客戶名稱自動匹配 */
function customerAutoComplete(){
    $("#customerFullName").autocomplete(
        encodeURI("/approvalajax/salesOrderApproval_findCustomerList"), {
        tableHead: "<div><span class='col-1'>客戶編碼</span>"
                 + "<span class='col-2'>客戶名稱</span></div>",
        minChars: 0,
        width: 310,
        multiple: false,
        mustMatch: false,
        matchContains: false,
        matchSubset: false,
        autoFill: false,

        // 關鍵:每次觸發前動態更新 ledger
        onBegin: function(options) {
            options.extraParams.ledger = $("#ledger").val();
            return options;
        },

        dataType: 'json',
        parse: function(data) {
            var rows = [];
            if (data == null || data.customerList == null) { return rows; }
            for (var i = 0; i < data.customerList.length; i++){
                rows[rows.length] = {
                    data:   data.customerList[i],
                    value:  data.customerList[i].cusName,
                    result: data.customerList[i].cusName
                };
            }
            return rows;
        },
        formatItem:   function(row, i, max) { /* 略 */ },
        formatMatch:  function(row, i, max) { return row.cusCode + row.cusName; },
        formatResult: function(row) { return row.cusName; }
    }).result(function(e, data, value, sec){
        clearCustomerInfo();
        $("#customerShortName").val(data.cusAbbName);
        $("#customerFullName").val(data.cusName);
        $("#customerCode").val(data.cusCode);
        $("#licensecode").val(data.licensecode);
        setPLAndPCAndCP(data.cusCode);
    }).bind("unmatch", function(){ clearCustomerInfo(); });
}

改動整理起來就是:defaults 多一個 onBegin、onChange 開頭判斷並合併回傳值、呼叫時在 onBegin 裡寫入業務邏輯。這樣一來,extraParams 甚至其他 options 都能動態調整,可謂一魚多吃。

更多 jQuery 相關內容可參考本站專題:《jQuery 視窗操作技巧總結》、《jQuery 拖拽特效與技巧總結》、《jQuery 常用插件及用法總結》、《jQuery 中 Ajax 用法總結》、《jQuery 表格操作技巧匯總》、《jQuery 擴展技巧總結》與《jQuery 選擇器用法總結》。

希望本文所述對你的 jQuery 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved