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

让jQuery Ajax代码更高效合理的优化方案咨询

优化方案

第一步:调整HTML结构

移除行内onclick绑定,用自定义属性存储请求参数和目标元素ID,同时修复原按钮ID重复的问题:

<ul class="list-unstyled" id="var_adjectives"><li><a href='#'>Loading...</a></li></ul>
<button class="refresh-btn" data-u="37" data-n="1" data-target="var_adjectives">Refresh</button>
<hr />

<ul class="list-unstyled" id="var_brands"><li><a href='#'>Loading...</a></li></ul>
<button class="refresh-btn" data-u="37" data-n="33" data-target="var_brands">Refresh</button>
<hr />

<ul class="list-unstyled" id="var_clothes"><li><a href='#'>Loading...</a></li></ul>
<button class="refresh-btn" data-u="37" data-n="67" data-target="var_clothes">Refresh</button>
<hr />

第二步:编写通用请求函数

整个项目只需要1个核心请求函数,所有模块复用:

function loadContent(targetId, u, n) {
    $.post('ajax.php', {u: u, n: n}, function(data) {
        $('#' + targetId).html(data.output);
    }, 'json');
}

第三步:简化初始化加载逻辑

把所有模块的配置存到数组里,循环初始化,不需要写30条重复的post请求:

$(document).ready(function(){
    // 所有模块配置,新增模块只需添加一行配置项即可
    const moduleList = [
        {target: 'var_adjectives', u: 37, n: 1},
        {target: 'var_brands', u: 37, n: 33},
        {target: 'var_clothes', u: 37, n: 67}
        // 剩余27个模块直接在数组里追加配置即可
    ];
    // 循环加载所有模块内容
    moduleList.forEach(module => loadContent(module.target, module.u, module.n));

    // 统一绑定所有刷新按钮的点击事件
    $(document).on('click', '.refresh-btn', function() {
        const $btn = $(this);
        loadContent($btn.data('target'), $btn.data('u'), $btn.data('n'));
    });
});

方案优势

  • 无冗余代码,核心逻辑仅写1次,30个模块也不需要额外新增函数
  • 后续新增模块只需两步:添加对应HTML结构、在moduleList数组里新增一行配置,无需修改JS逻辑
  • 替换了不合理的行内onclick绑定,改用事件委托实现,哪怕后续动态新增的刷新按钮也能自动适配,不需要重新绑定事件
  • 可维护性极强,后续如果需要添加加载状态、错误处理、请求超时等逻辑,只需修改loadContent一个函数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:54:00