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

如何通过AJAX将Web API数据渲染至HTML统计面板?

嘿,这个需求我之前也帮人搞过,其实挺简单的,分两种方案给你参考,看你习惯用原生JS还是jQuery:

方案1:原生JavaScript实现(无依赖)

如果不想引入jQuery之类的库,用浏览器原生的fetch API就能搞定,还可以自己写个简单的数字递增动画,效果和counter-up插件差不多:

// 先写个数字递增的动画函数,可自定义速度和步数
function counterUp(element, targetNum) {
  let currentNum = 0;
  // 计算每步递增的数值,步数越多动画越平滑
  const step = Math.ceil(targetNum / 60); 
  const timer = setInterval(() => {
    currentNum += step;
    if (currentNum >= targetNum) {
      currentNum = targetNum;
      clearInterval(timer);
    }
    // 加上千分位分隔,看起来更专业
    element.textContent = currentNum.toLocaleString();
  }, 15); // 每15毫秒更新一次,调大数值会变慢
}

// 发起API请求获取数据
fetch('https://subdomain.mywebsite.com/portal/statistics')
  .then(res => {
    if (!res.ok) throw new Error('请求失败,请检查API地址');
    return res.json();
  })
  .then(stats => {
    // 获取页面上的四个统计元素
    const onlineEl = document.getElementById('online');
    const registeredEl = document.getElementById('registered');
    const todayEl = document.getElementById('connectedtoday');
    const lastMonthEl = document.getElementById('connectedlastmonth');

    // 注意!API返回的部分数值是字符串,要转成数字再用
    counterUp(onlineEl, parseInt(stats.onlineUsers));
    counterUp(registeredEl, parseInt(stats.registeredUsers));
    counterUp(todayEl, stats.connectedTodayOnWebsite); // 这个本来就是数字
    counterUp(lastMonthEl, parseInt(stats.connectedLastMonth));
  })
  .catch(err => {
    console.error('加载统计数据出错:', err);
    // 请求失败时显示默认占位符,避免页面空着
    [onlineEl, registeredEl, todayEl, lastMonthEl].forEach(el => {
      if(el) el.textContent = '--';
    });
  });
方案2:jQuery配合counter-up插件实现

如果你已经在项目里用了jQuery,而且想直接用现成的counter-up插件(比如jquery.counterup.js,需要配合waypoints.js),代码会更简洁:

首先记得给你的四个span标签加上class="counter",这样插件能识别到:

<span id="online" class="counter"></span>
<span id="registered" class="counter"></span>
<span id="connectedtoday" class="counter"></span>
<span id="connectedlastmonth" class="counter"></span>

然后写JS代码:

$(document).ready(function() {
  $.ajax({
    url: 'https://subdomain.mywebsite.com/portal/statistics',
    type: 'GET',
    dataType: 'json',
    success: function(stats) {
      // 先把数值填充到对应元素
      $('#online').text(stats.onlineUsers);
      $('#registered').text(stats.registeredUsers);
      $('#connectedtoday').text(stats.connectedTodayOnWebsite);
      $('#connectedlastmonth').text(stats.connectedLastMonth);

      // 触发counter-up动画,参数可以自己调
      $('.counter').counterUp({
        delay: 10, // 每步的延迟时间
        time: 1200 // 动画总时长(毫秒)
      });
    },
    error: function(xhr, status, err) {
      console.error('统计数据加载失败:', err);
      // 失败时显示占位符
      $('.counter').text('--');
    }
  });
});

几个关键提醒

  1. 数据类型转换:API返回的onlineUsers、registeredUsers、connectedLastMonth是字符串,一定要转成数字再给动画用,不然会出问题!
  2. 跨域问题:如果你的主网站和API子域名不同源,得让API服务器配置CORS响应头,比如Access-Control-Allow-Origin: 你的主站域名,不然浏览器会拦截请求。
  3. 错误处理:一定要加错误捕获逻辑,不然API挂了页面上的统计位就空着,体验很差。

内容的提问来源于stack exchange,提问作者Andrew S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:49:51