JavaScript获取展示GET表单提交跨页参数的问题咨询
问题原因
- 参数大小写不匹配:Page2表单提交的字段名为小写
login/password,Page1中使用大写LOGIN/PASSWORD读取参数,导致无法识别提交的参数 - 逻辑优先级错误:Page1的JS代码未做参数存在判断,无论是否有外部传入参数,都会强制覆盖为默认值,导致表单提交的参数被冲掉
- 语法&配置错误:Page1的
body标签存在多余引号的语法错误,且JS文件引用路径和实际文件名不匹配;Page2的密码输入框重复定义了type属性
修复方案
1. 修正Page1.html代码
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 修正JS文件路径,和实际文件名一致 --> <script defer src="Page1_main.js"></script> <title>Document</title> </head> <!-- 修正body标签多余引号的语法错误 --> <body> <div> <h1>Nous avons reçu : </h1> <h2 style="display: inline-block">LOGIN : </h2> <p style="display: inline-block" id="login"></p> </div> <div > <h2 style="display: inline-block">PASSWORD : </h2> <p style="display: inline-block" id="password"></p> </div> </body> </html>
2. 修正Page1_main.js代码
const url = new URL(window.location.href); const params = url.searchParams; // 新增参数判断逻辑:有外部传参就用传参,没有再设置默认值 const loginVal = params.get('login') ?? 'Licois'; const pwdVal = params.get('password') ?? 'Johanne'; // 只有用默认值的时候才更新地址栏参数 if (!params.has('login')) params.set('login', loginVal); if (!params.has('password')) params.set('password', pwdVal); window.history.replaceState({}, '', location.pathname + '?' + params.toString()); // 调整alert逻辑展示实际参数值 if (params.has('login')) { alert(`${loginVal} !`); } else { alert("Licois est introuvable !") } if (params.has('password')) { alert(`${pwdVal} !`); } else { alert("Johanne a disparu !") } document.getElementById("login").innerHTML = loginVal; document.getElementById("password").textContent = pwdVal;
3. 可选优化Page2.html代码(修正冗余属性)
<!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Exercice 2</title> </head> <body> <form action="Page1.html" method="GET"> <label for="login">Login</label> <input type="text" name="login" id="login" > <div><br></div> <label for="password">Password</label> <!-- 修正重复的type属性,删除冗余的for属性 --> <input type="password" name="password" id="password"> <div><br></div> <button type="submit" id="envoyer">Envoyer</button> </form> </body> </html>
效果说明
- 直接访问Page1.html时,会自动填充默认的账号密码,地址栏同步显示默认参数
- 从Page2提交表单到Page1时,会优先展示提交的账号密码,地址栏保留提交的参数值,不会被默认值覆盖
内容的提问来源于stack exchange,提问作者Ruan
相关产品推荐
相关产品推荐

