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

如何获取HTML select下拉框选中文本并通过AJAX提交到PHP存入数据库

问题原因

你遇到的问题是变量作用域导致的,在change事件回调中用let声明的construidoSelected是块级局部变量,仅在change事件的回调函数内部可访问,表单提交的回调函数无法读取该局部变量。

最优解决方案

直接在表单提交时实时获取下拉框选中文本即可,无需额外监听change事件存储变量,修改后的代码如下:

let start = 0, url = "http://localhost:8077/connectpost/validations/sendinterview.php";
$(document).ready(function () {
    $('#form_interview').submit(function (e) {
        // 直接在提交时获取下拉框选中文本
        let construidoSelected = $("#construido option:selected").text();
        $.post(url, {
            fuente:"",
            construido: construidoSelected,
            recibir: $("#recibir-agua").val(),
            horas: $("#horas-agua").val(),
        });
        $("#recibir").val("");
        $("#horas").val("");
        return false;
    })
});
可选方案:保留change事件存储变量

如果业务需要提前存储选中值,可以把变量声明提升到两个回调都能访问的外层作用域:

// 在外层作用域声明变量
let construidoSelected = '';
$(document).on('change', '#construido', function () {
    // 直接赋值,不要加let重新声明局部变量
    construidoSelected = $("#construido option:selected").text()
});

let start = 0, url = "http://localhost:8077/connectpost/validations/sendinterview.php";
$(document).ready(function () {
    $('#form_interview').submit(function (e) {
        $.post(url, {
            fuente:"",
            construido: construidoSelected,
            recibir: $("#recibir-agua").val(),
            horas: $("#horas-agua").val(),
        });
        $("#recibir").val("");
        $("#horas").val("");
        return false;
    })
});

内容的提问来源于stack exchange,提问作者Ander Canales Medina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:15:03