利用微信插件实现下拉列表(二)
作者:杨锦龙时间:2026-01-19点击量:0次
<div class="layui-form-item">
<label class="layui-form-label">预约时间</label>
<div class="layui-input-inline">
<input class="layui-input" autocomplete="off" readonly="readonly" id="time" lay-verify="apply_time" placeholder="请选择预约日期" type="text" name="apply_time">
</div>
</div>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="https://res.wx.qq.com/t/wx_fed/weui.js/res/1.2.17/weui.min.js"></script>
<script>
let cachedTimeSlots = null;
document.getElementById('time').addEventListener('click', function () {
const $input = this;
if (cachedTimeSlots) {
showTimePicker(cachedTimeSlots, $input);
return;
}
const loading = weui.loading('加载中...');
fetch('/member/Api/getTimeList').then(res => res.json()).then(json => {
loading.hide();
if (json.code === 100 && Array.isArray(json.data)) {
// ✅ 关键:把字符串数组转成 { label, value } 对象数组
cachedTimeSlots = json.data.map(slot => ({
label: slot, // 必须有 label!
value: slot
}));
showTimePicker(cachedTimeSlots, $input);
} else {
weui.alert(json.msg || '加载时间段失败');
}
console.log('Raw data:', json.data);
console.log('Mapped data:', cachedTimeSlots);
})
.catch(err => {
console.error('Error:', err);
loading.hide();
weui.alert('网络错误');
});
});
function showTimePicker(data, input) {
// ✅ 注意:weui.picker 需要 [[{label,value}, ...]] —— 二维数组!
weui.picker(data, {
title: '请选择预约时间',
onConfirm: function (result) {
// result 是一个数组,长度等于列数(这里1列)
// result[0] 是选中的对象
if (result && result[0]) {
input.value = result[0].label; // 显示 label
// 如果需要,也可以存 value 到隐藏域
// document.getElementById('time_value').value = result[0].value;
}
}
});
}
</script>数据格式如下:
{
"code": 100,
"data": [
"09:30 - 10:00",
"10:00 - 10:30",
"10:30 - 11:00",
"11:00 - 11:30",
"11:30 - 12:00",
"13:30 - 14:00",
"14:00 - 14:30",
"14:30 - 15:00",
"15:00 - 15:30",
"15:30 - 16:00",
"16:00 - 16:30",
"16:30 - 17:00",
"17:00 - 17:30",
"17:30 - 18:00"
]
}