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

请求协助:将date类型输入转为dd/mm/yyyy格式文本并实现URL传参

解决方案:将Date类型输入转为dd/mm/yyyy格式并通过URL传递参数

完整可运行代码

<div class="container">
<form class="horizontal" action="https://homirent.cloudbeds.com/#/" method="get">
<p class="p1"> City: <select name="city">
<option value="all">All Cities</option>
<option>Cancún</option>
<option>Ciudad De México</option>
<option>Santiago De Querétaro</option>
</select>
Check-In:
<input type="date" name="check_in" />
Check-Out:
<input type="date" name="check_out" />
  <input type="submit" /> </p>
</form>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
// 日期转换函数:将yyyy-mm-dd格式转为dd/mm/yyyy
function formatDate(dateStr) {
  const [year, month, day] = dateStr.split('-');
  return `${day}/${month}/${year}`;
}

$("form").on("submit", function(event) {
  event.preventDefault();
  
  // 获取表单各字段值
  const city = $(this).find('select[name="city"]').val();
  const checkInRaw = $(this).find('input[name="check_in"]').val();
  const checkOutRaw = $(this).find('input[name="check_out"]').val();
  
  // 转换日期格式
  const checkInFormatted = formatDate(checkInRaw);
  const checkOutFormatted = formatDate(checkOutRaw);
  
  // 构建查询参数
  const params = new URLSearchParams();
  params.append('city', city);
  params.append('check_in', checkInFormatted);
  params.append('check_out', checkOutFormatted);
  
  // 拼接完整URL并跳转
  const url = $(this).attr('action') + '?' + params.toString();
  window.location.href = url;
});
</script>

关键修改说明

  • 替换输入类型:把原type="text"的日期输入改为type="date",浏览器会自动显示日历选择控件,且返回值固定为yyyy-mm-dd格式。
  • 日期转换函数:通过拆分yyyy-mm-dd字符串,重新拼接成dd/mm/yyyy格式,规避手动截取字符串的错误(你之前尝试里把参数名写错成checkin,实际是check_in,这也是核心问题之一)。
  • 手动构建参数:放弃使用serialize()(它会直接传递yyyy-mm-dd格式的日期),改用URLSearchParams安全拼接参数,自动处理编码问题,省去手动替换+的麻烦。
  • 参数名校验:严格匹配目标URL要求的参数名(check_in和check_out),避免拼写错误导致参数无法识别。

之前尝试失效的原因

  1. 参数名错误:代码里写的是checkin=,但实际表单参数名是check_in=,导致无法正确截取日期值。
  2. 字符串截取逻辑错误:substring的第二个参数是结束位置而非长度,写10无法获取完整的日期字符串。
  3. 手动拼接参数易出错:直接截取字符串拼接参数极易破坏原有参数结构,改用URLSearchParams更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:20:35