如何将JS变量值赋值给Java变量?DBname打印返回空值求助
问题原因与解决方案
核心问题:前后端执行时机完全错位
你当前的写法混淆了服务器端Java代码和浏览器端JavaScript代码的执行顺序:
- Java代码是在服务器渲染页面时就执行完毕的,此时前端页面还没发送到浏览器,用户还没选择下拉框,自然拿不到任何前端变量值。
- JavaScript代码是在浏览器加载页面后才运行的,此时服务器端的Java代码早就执行完了,两者完全无法直接交互。
另外你的代码还有两个基础错误:
document.getElementsByName('DB')返回的是元素集合,不是选中值,需要用[0].value获取选中的数据库名- 初始化
String Tablenames[]=new String[0];后直接赋值会触发数组越界异常,应该用动态集合存储表名
正确实现步骤
1. 修正前端代码:监听下拉框变化,发送请求给后端
把option的onclick改成select的onchange事件,通过HTTP请求把选中的数据库名传给后端:
<select name="DB" id="dbSelect" style="font-size:20px"> <option value="findmaximum">findmaximum</option> <option value="marklist">marklist</option> </select> <script> // 监听下拉框选择变化 document.getElementById('dbSelect').addEventListener('change', function() { // 获取选中的数据库名 const selectedDB = this.value; // 用fetch发送POST请求到后端接口 fetch('/getTableList', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, // 编码参数避免乱码 body: `dbName=${encodeURIComponent(selectedDB)}` }) .then(response => response.json()) .then(data => { // 拿到后端返回的表名后,执行前端渲染逻辑 console.log("获取到的表名列表:", data.tableNames); // 示例:动态生成表名下拉框 // const select = document.createElement('select'); // data.tableNames.forEach(name => { // const option = document.createElement('option'); // option.value = name; // option.textContent = name; // select.appendChild(option); // }); // document.body.appendChild(select); }) .catch(err => console.error("请求失败:", err)); }); </script>
2. 后端Java代码:接收参数,查询表名并返回结果
写一个Servlet(或Spring Controller)接收前端请求,处理数据库查询后返回JSON结果:
@WebServlet("/getTableList") public class TableListServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应格式为JSON response.setContentType("application/json;charset=UTF-8"); // 获取前端传递的数据库名参数 String dbName = request.getParameter("dbName"); System.out.println("前端选中的数据库:" + dbName); List<String> tableNames = new ArrayList<>(); // 执行数据库查询 try (ResultSet rs = DBconnector.tables(dbName)) { while (rs.next()) { tableNames.add(rs.getString("TABLE_NAME")); } } catch (SQLException e) { e.printStackTrace(); } // 把表名列表转成JSON返回给前端 ObjectMapper mapper = new ObjectMapper(); Map<String, Object> result = new HashMap<>(); result.put("tableNames", tableNames); mapper.writeValue(response.getWriter(), result); } }
关键说明
- 前后端数据交互必须通过HTTP请求(GET/POST等)完成,不能直接在JavaScript中嵌入Java代码获取前端变量
- 用
List替代固定长度数组存储表名,避免数组越界问题 - 对请求参数进行编码处理,防止中文或特殊字符乱码
内容的提问来源于stack exchange,提问作者SENTHILKUMAR S
相关产品推荐
相关产品推荐

