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

页面重载后,如何保留未更换办公室时AJAX加载的员工选中值?

问题:页面刷新后恢复AJAX加载的员工下拉框选中值

我实现了如下功能:当用户在下拉框中选择办公室后,另一个下拉框会通过AJAX加载该办公室的员工。现在遇到的问题是:当点击「确认」按钮导致页面加载后,若未更换办公室,如何存储并恢复之前选中的员工值?

以下是我的代码:

$( document ).ready(function() { 
    var $option = $('#office_id').find('option:selected'); 
    var value = $option.val(); 
    updateSalesDay(value); 

    $('#office_id').change(function(e){ 
        var $option = $(this).find('option:selected'); 
        var value = $option.val(); 
        updateSalesDay(value); 
        console.log(value); 
    }); 
}); 

function updateSalesDay(office_id){ 
    $('.load-bar').css('display','block'); 
    $('.panel-body').css('pointer-events','none'); 
    $('#employee_id').empty(); 
    $.ajax({ 
        type: "POST", 
        headers: { 
            'X-CSRF-TOKEN': $('[name="csrf-token"]').attr('content') 
        }, 
        url: "{{ route('postFilterEmployee') }}", 
        data: { 'office_id': office_id }, 
        dataType: 'json', 
        success: function (data) { 
            console.log(data); 
            employeesList = data; 
            if (employeesList.length === 0) { 
                $('#employee_id').append('<option></option>'); 
            }else{ 
                $('#employee_id').append('<option></option>'); 
                for (index = 0; index < employeesList.length; index++) { 
                    $('#employee_id').append('<option value="'+employeesList[index].id+'">'+employeesList[index].last_name+' '+employeesList[index].first_name+'</option>'); 
                } 
            } 
            $('.load-bar').css('display','none'); 
            $('.panel-body').css('pointer-events',''); 
        }, 
        error: function (data) { 
            console.log(data); 
        } 
    }); 
}

解决方案

这个问题的核心是在页面刷新前保存用户的选择状态,加载时再恢复,我给你两种可靠的实现方案,你可以根据场景选择:

方案一:用本地存储(localStorage)快速实现

这种方式不需要后端配合,纯前端就能搞定,适合页面刷新后需要保留选择的场景:

修改后的代码:

$(document).ready(function() {
    // 读取之前存储的选中值
    const savedOfficeId = localStorage.getItem('selectedOfficeId');
    const savedEmployeeId = localStorage.getItem('selectedEmployeeId');
    
    // 优先用存储的办公室ID,没有则用默认选中的
    let initialOfficeId = savedOfficeId || $('#office_id').find('option:selected').val();
    
    // 加载员工时传入预选中的员工ID
    updateSalesDay(initialOfficeId, savedEmployeeId);

    $('#office_id').change(function(e) {
        const selectedOfficeVal = $(this).find('option:selected').val();
        // 存储当前选中的办公室ID
        localStorage.setItem('selectedOfficeId', selectedOfficeVal);
        // 切换办公室后,清空之前的员工选择(避免无效ID)
        localStorage.removeItem('selectedEmployeeId');
        updateSalesDay(selectedOfficeVal);
        console.log(selectedOfficeVal);
    });

    // 监听员工下拉框的选择,实时存储选中值
    $('#employee_id').change(function() {
        const selectedEmpId = $(this).val();
        localStorage.setItem('selectedEmployeeId', selectedEmpId);
    });
});

// 新增preSelectedEmpId参数,用于恢复选中状态
function updateSalesDay(office_id, preSelectedEmpId = null) {
    $('.load-bar').css('display','block');
    $('.panel-body').css('pointer-events','none');
    $('#employee_id').empty();
    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': $('[name="csrf-token"]').attr('content')
        },
        url: "{{ route('postFilterEmployee') }}",
        data: { 'office_id': office_id },
        dataType: 'json',
        success: function (data) {
            console.log(data);
            const employeesList = data;
            $('#employee_id').append('<option></option>');
            
            if (employeesList.length > 0) {
                for (let index = 0; index < employeesList.length; index++) {
                    const emp = employeesList[index];
                    // 用模板字符串更易读
                    $('#employee_id').append(`<option value="${emp.id}">${emp.last_name} ${emp.first_name}</option>`);
                }
                // 如果有预选中的员工ID,自动选中
                if (preSelectedEmpId) {
                    $('#employee_id').val(preSelectedEmpId);
                }
            }
            
            $('.load-bar').css('display','none');
            $('.panel-body').css('pointer-events','');
        },
        error: function (data) {
            console.log(data);
        }
    });
}

关键说明:

  • 用localStorage持久化存储选中的办公室和员工ID,页面刷新后依然能读取
  • 切换办公室时清空员工ID的存储,避免新办公室里没有该员工导致选中失败
  • 在updateSalesDay的成功回调里,加载完员工列表后自动设置选中状态

方案二:结合后端旧输入值(更适合表单提交场景)

如果你的「确认」按钮是提交表单,那用Laravel的old()方法获取之前提交的值会更可靠(不会受清除本地存储的影响):

步骤1:在Blade模板中添加隐藏域

<!-- 存储上次提交的办公室和员工ID -->
<input type="hidden" id="saved_office_id" value="{{ old('office_id', $office->id ?? '') }}">
<input type="hidden" id="saved_employee_id" value="{{ old('employee_id') }}">

步骤2:修改JS读取隐藏域的值

$(document).ready(function() {
    // 从隐藏域读取后端传递的旧值
    const savedOfficeId = $('#saved_office_id').val() || $('#office_id').find('option:selected').val();
    const savedEmployeeId = $('#saved_employee_id').val();
    
    updateSalesDay(savedOfficeId, savedEmployeeId);

    // 后面的change事件逻辑和方案一一致,只是存储可以换成更新隐藏域,或者依然用localStorage
});

这种方式的好处是和表单提交的状态绑定,更符合后端驱动的应用场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:19:32