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

如何通过JavaScript向API URL传递动态日期参数?

解决方案

当然可以用JavaScript实现,你之前的问题是把变量名用单引号包裹,导致API接收到的是字符串'startdateOutlay'而非输入框的实际值。以下是具体实现步骤:

1. 基础HTML结构示例

假设你的日历输入框和触发按钮结构如下:

<input type="date" id="startdateOutlay">
<input type="date" id="enddateOutlay">
<button onclick="fetchFilteredData()">查询数据</button>

2. 核心JavaScript逻辑

function fetchFilteredData() {
    // 获取日历输入框的实际值
    const startDate = document.getElementById('startdateOutlay').value;
    const endDate = document.getElementById('enddateOutlay').value;

    // 先验证日期是否填写完整
    if (!startDate || !endDate) {
        alert('请选择完整的开始和结束日期');
        return;
    }

    // 动态拼接符合要求的API URL
    const baseApiUrl = 'http://127.0.0.1:8000/api/outlay';
    const targetUrl = `${baseApiUrl}?startdate=${startDate}&enddate=${endDate}`;

    // 发起请求并处理返回数据
    fetch(targetUrl)
        .then(response => response.json())
        .then(data => {
            console.log('筛选后的数据:', data);
            // 这里可以添加数据渲染到页面的逻辑
        })
        .catch(error => {
            console.error('请求出错:', error);
        });
}

关键注意事项

  • 不要给变量名加单引号:直接将获取到的日期值拼接进URL,API才能识别为正确的日期参数
  • 利用type="date"的输入框特性:这种输入框返回的value天然是YYYY-MM-DD格式,完全匹配你需要的参数格式
  • 可选的日期格式处理:如果你的日历组件返回非标准格式,可以用下面的函数转换:
function formatToYYYYMMDD(dateStr) {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:25:05