You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Ajax搜索结果绑定到TextField并阻止页面刷新?

问题解决:Ajax搜索结果点击后赋值输入框并阻止页面刷新

问题根源

  1. 页面刷新:生成的搜索结果使用了<a href="">标签,点击时会触发默认跳转行为(空href会刷新当前页面)。
  2. 无法赋值:未给结果项绑定点击事件,无法将选中内容同步到搜索输入框。

解决步骤

1. 消除默认跳转

直接移除<a>标签(此处仅需选择功能,无需跳转),用<div>作为结果项容器,避免触发页面刷新。

2. 绑定点击赋值逻辑

由于搜索结果是动态生成的,采用事件委托在父容器resultBox上监听点击事件,确保所有后续生成的结果项都能触发赋值逻辑。

修改后的完整代码

console.log("Sanity check!");
const url = window.location.href
window.onload = function() {
const searchForm = document.getElementById("search-form")
const searchInput = document.getElementById("search-box")
const resultBox = document.getElementById("results-box")
const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value

const sendSearchData = (stock_name) =>{
    $.ajax({
        type: "POST",
        url: '',
        data:{
            'csrfmiddlewaretoken' : csrf,
            'stock_name':stock_name
        },
        success: (res) =>{
            console.log(res.data)
            const data = res.data
            if (Array.isArray(data))
            {  
                resultBox.innerHTML= ""
                data.forEach(stock_name =>{
                    // 替换a标签为带类名的div,标记可点击项
                    resultBox.innerHTML += `
                       <div class="search-result-item" style="cursor: pointer; padding: 8px; border-bottom: 1px solid #eee;">
                       <p> ${stock_name.symbol_name} </p>
                       <small> ${stock_name.symbol}</small>
                       </div>
                    `
                })
            }
            else
            {
                if (searchInput.value.length > 0)
                {
                    resultBox.innerHTML =`<b>${data}</b>`
                }
                else
                {
                    resultBox.classList.add('not-visible')
                }
            }

        },
        error: (err) =>{
            console.log(err)
        }
    })
}

searchInput.addEventListener('keyup',e=>{
    console.log(e.target.value)
    if (resultBox.classList.contains('not-visible')){
        resultBox.classList.remove('not-visible')
    }
    sendSearchData(e.target.value)
})

// 事件委托处理结果项点击
resultBox.addEventListener('click', function(e) {
    const resultItem = e.target.closest('.search-result-item');
    if (!resultItem) return;

    // 获取选中的symbol_name文本,可根据需求替换为symbol
    const selectedValue = resultItem.querySelector('p').textContent.trim();
    searchInput.value = selectedValue;
    // 点击后隐藏结果框(可选逻辑)
    resultBox.classList.add('not-visible');
})

}

补充说明

  • 给结果项添加了基础样式,提升交互辨识度;
  • 若需保留<a>标签,需在点击事件中添加e.preventDefault()阻止跳转,同时调整事件委托的目标元素;
  • 点击后隐藏结果框为可选逻辑,可根据业务需求删除。

内容的提问来源于stack exchange,提问作者Satheesh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 21:38:39