萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

AJAX 實現輸入框即時下拉建議:汽車品牌/廠商搜尋範例

功能需求

  • 使用者輸入品牌/廠商名稱
  • 即時發送 AJAX 請求,後端模糊查詢
  • 下拉列表顯示匹配結果,點選填入輸入框並帶入隱藏 ID
  • 相容 IE (onpropertychange) 與現代瀏覽器 (input 事件)

前端架構

<!-- HTML 片段 -->
<input type="text" id="generalBrandName" name="generalBrandName" 
       onfocus="showList('List1')" onblur="hideList('List1')">
<input type="hidden" id="brandIdGeneral" name="brandIdGeneral">

<div class="dropdown" id="List1">
  <div class="dropdown-content" id="ListLi1"></div>
</div>

<!-- 第二組:廠商 -->
<input type="text" id="brandName" ...>
<input type="hidden" id="brandId" ...>
<div class="dropdown" id="List2"><div id="ListLi2"></div></div>

CSS 樣式 (關鍵類別)

.dropdown {
  position: absolute; display: none; z-index: 100;
  width: 180px; max-height: 120px; overflow-y: auto;
  border: 1px solid #666; background: #eee;
}
.dropdown-content ul { margin: 0; padding: 0; list-style: none; }
.dropdown-content li {
  padding: 5px 10px; cursor: pointer; border-bottom: 1px dashed #999;
}
.dropdown-content li:hover { background: #0099cc; color: white; }

JavaScript 核心邏輯 (jQuery)

// 全域快取上次值,避免重複請求
var lastBrandVal = '', lastMfrVal = '';

// 綁定輸入事件 (相容 IE/現代瀏覽器)
$(function() {
  $('#generalBrandName, #brandName').each(function() {
    var $input = $(this);
    if ('onpropertychange' in this) { // IE
      $input.on('propertychange', function(e) {
        if (e.originalEvent.propertyName === 'value') onInputChange($input);
      });
    } else { // 標準
      $input.on('input', function() { onInputChange($input); });
    }
  });
});

function onInputChange($input) {
  var val = $input.val();
  var listId, hiddenId, apiUrl;
  
  if ($input.is('#generalBrandName')) {
    if (val === lastBrandVal) return;
    lastBrandVal = val;
    listId = 'ListLi1'; hiddenId = 'brandIdGeneral';
    apiUrl = '/car/carmodel/brandSearch.do';
  } else {
    if (val === lastMfrVal) return;
    lastMfrVal = val;
    listId = 'ListLi2'; hiddenId = 'brandId';
    apiUrl = '/car/carmodel/mfrSearch.do';
  }
  
  if (!val.trim()) { hideList(listId.replace('Li','')); return; }
  
  // 發送 AJAX (雙重 encodeURIComponent 防特殊字元)
  $.getJSON(apiUrl, {
    keyWord: encodeURIComponent(encodeURIComponent(val)),
    _: Date.now()  // 防快取時間戳
  }, function(data) {
    renderList(listId, data, $input.attr('id'), hiddenId);
    showList(listId.replace('Li',''));
  });
}

function renderList(containerId, items, inputId, hiddenId) {
  var $container = $('#' + containerId).empty();
  var $ul = $('
    '); $.each(items, function(i, item) { var name = item.brandNameGeneral || item.brandName; var id = item.brandIdGeneral || item.brandId; var $li = $('
  • ').text(name).css('cursor', 'pointer'); $li.on('mousedown', function() { // mousedown 比 click 先觸發,搶在 blur 前 $('#' + inputId).val(name); $('#' + hiddenId).val(id); hideList(containerId.replace('Li','')); }); $ul.append($li); }); $container.append($ul); } function showList(id) { $('#' + id).show(); } function hideList(id) { // 延遲隱藏,讓 mousedown 先觸發 setTimeout(function() { $('#' + id).hide(); }, 200); }

後端介面規約 (JSON)

// 請求: GET /car/carmodel/brandSearch.do?keyWord=xxx&_=timestamp
// 回應:
[
  {"brandIdGeneral": "101", "brandNameGeneral": "BMW"},
  {"brandIdGeneral": "102", "brandNameGeneral": "Benz"}
]

關鍵細節總結

細節處理方式
事件相容IE `propertychange` + 標準 `input` 事件
防抖/去重全域變數記錄上次值,相同則不請求
防快取時間戳參數 `_` + `$.getJSON` 內建 `cache: false`
編碼安全雙重 `encodeURIComponent` 處理特殊字元
點選優先`mousedown` 搶在輸入框 `blur` 前執行
隱藏延遲`setTimeout 200ms` 確保點選生效
鍵盤支援補充 `keydown` (上下鍵選擇、Enter 確認、Esc 關閉)

現代化替代:原生 `` / 第三方庫

<input list="brands" id="brandInput">
<datalist id="brands">
  <option value="BMW"></option>
  <option value="Benz"></option>
</datalist>
  • 原生 ``:無 JS 依賴、但樣式難控制、無 ID 關聯、大量資料效能差
  • 推薦庫:Select2、Tom Select、Choices.js、Vue/Angular/React 組件庫
copyright © 萬盛學電腦網 all rights reserved