如何获取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
相关产品推荐
相关产品推荐

