jQuery页面重定向后获取表单提交数据返回undefined的问题排查
问题原因拆解
- 取数逻辑完全失效:在
gamescreen.html的JS代码里用$('#p1').val()、$('#p2').val()获取玩家名字时,这两个ID对应的输入框仅存在于首页表单中。跨页面跳转后,浏览器会完全加载新的页面DOM,首页的所有元素都不存在于游戏页的DOM结构里,jQuery无法选中对应节点,自然返回undefined。 - 静态页面无法承接POST数据:使用原生表单的POST方法提交时,传递的参数会被放在HTTP请求体中。因为
gamescreen.html是纯静态文件,没有后端服务解析请求体的内容,这些提交的参数不会被注入到页面上下文中,前端JS也没有权限直接读取请求体里的POST内容,最终造成数据丢失的效果。
无后端的适配解决方案
不需要搭建任何服务端,只用浏览器自带的本地存储能力就能实现跨页玩家姓名传递,修改内容如下:
首页代码调整
移除form的原生POST提交配置,加JS拦截提交动作,把玩家姓名存在本地存储后再手动跳转:
<h1 id="start">Welcome to Noah's Connect Four Game!</h1> <form id="playerEntryForm"> <label for="p1">Enter Player One's Name:</label><br> <input type="text" id="p1" placeholder="Player One" ><br><br> <label for="p2">Enter Player Two's Name:</label><br> <input type="text" id="p2" placeholder="Player Two"><br><br> <input type="submit" value="Play Now!"> </form> <script> document.getElementById('playerEntryForm').addEventListener('submit', function(e) { // 阻止表单默认的POST跳转 e.preventDefault(); // 读取输入值,空值就用默认占位符内容兜底 const p1Name = document.getElementById('p1').value.trim() || 'Player One'; const p2Name = document.getElementById('p2').value.trim() || 'Player Two'; // 存到浏览器本地存储 localStorage.setItem('connect4_p1', p1Name); localStorage.setItem('connect4_p2', p2Name); // 手动跳转到游戏页 window.location.href = 'gamescreen.html'; }) </script>
游戏页代码调整
- 替换原来从DOM取数的逻辑,改为从本地存储读取玩家姓名
- 修正原代码里的回合提示反向bug:落完红色棋子后应该轮到对应第二玩家的回合,提示文案也要匹配对应棋子的颜色
let turn = ''; // 从本地存储读取玩家姓名,加兜底默认值 let usrOne = localStorage.getItem('connect4_p1') || 'Player One'; let usrTwo = localStorage.getItem('connect4_p2') || 'Player Two'; $('td').click(function() { if (turn == 'Red'){ $(this).css("background-color","red"); $(this).text("Red"); turn = 'Blue'; // 下一轮是Blue玩家的回合,显示对应玩家名字和颜色提示 $('p').text(`It's ${usrTwo} Turn! Place your blue chip in one of the columns!`); } else{ $(this).css("background-color","#3f5c94"); $(this).text("Blue"); turn = "Red"; // 下一轮是Red玩家的回合,显示对应玩家名字和颜色提示 $('p').text(`It's ${usrOne} Turn! Place your red chip in one of the columns!`); } })
内容的提问来源于stack exchange,提问作者NoahSmiley
相关产品推荐
相关产品推荐

