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

如何用jQuery实现无提交页面刷新?解决下拉框切换触发提交问题

解决DropDownList切换触发表单自动提交的问题

问题场景

我的布局页里有一个DropDownList,其他页面包含用户可提交的表单。原本期望用户切换DropDownList选项时页面能自动更新,但实际切换时页面会触发表单的自动提交行为。

原有实现代码

$(document).ready(function () {
    $("#Services").change(function (event) {
        var Servicecookie = getCookie("sid_Cookie");
        if (Servicecookie != null) {
            setCookie("sid_Cookie", $(this).val());
            $("#selectedService").html($("#Services option:selected").text());
        } else {
            setCookie("sid_Cookie", $(this).val());
            $("#selectedService").html($("#Services option:selected").text());
        }
        location.reload();
    });
});

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

问题原因

原来使用的location.reload()方法存在一个隐患:如果当前页面是通过POST请求加载的(比如用户刚提交过表单),浏览器会保留POST请求的上下文,重新加载时会触发表单的重复提交,这就是我们遇到的自动提交问题。

已验证的解决方案

通过获取当前页面URL并直接跳转至该URL,这样会触发页面的[HttpGet]请求,彻底避开POST请求的上下文,避免表单自动提交。修改后的关键代码如下:

$(document).ready(function () {
    $("#Services").change(function (event) {
        var Servicecookie = getCookie("sid_Cookie");
        if (Servicecookie != null) {
            setCookie("sid_Cookie", $(this).val());
            $("#selectedService").html($("#Services option:selected").text());
        } else {
            setCookie("sid_Cookie", $(this).val());
            $("#selectedService").html($("#Services option:selected").text());
        }
        // 替换原来的location.reload()
        var url = window.location.href;
        window.location.href = url;
    });
});

// getCookie和setCookie函数保持不变
function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

补充说明

直接跳转当前URL的方式,本质是发起一个全新的GET请求加载页面,浏览器不会保留之前的POST请求状态,因此既实现了切换DropDownList后页面更新的需求,又彻底避免了表单自动提交的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:37:55