表单返回错误时如何在同页面展示?IBMi CGIDEV2登录表单错误处理
最优实现方案
1 优先调整后端CGI逻辑(推荐)
当前用500错误表示账号密码校验失败不符合HTTP规范,也不利于后续维护,你可以修改flower.cgi的逻辑:
- 账号密码校验失败时,不要直接终止程序,先输出HTTP头指定状态码为401:
Status: 401 Unauthorized,再输出JSON格式提示信息后退出即可,示例返回内容:
{"status":"error","message":"IBMi UserID或密码错误"}
- 校验成功的逻辑保持不变即可。
2 前端修改为异步提交实现错误捕获
2.1 修改表单代码
给原表单添加id属性,新增错误提示容器,修改后表单代码如下:
<form id="loginForm" method="POST" action="/nature/flower.cgi"> <!-- Username input --> <div class="form-outline mb-4"> <input type="text" name="userid" id="form3Example3" class="form-control form-control-lg" style="text-transform:uppercase" placeholder="Enter a valid IBMi UserID" /> <label class="form-label" for="form3Example3">IBMi UserID</label> </div> <!-- Password input --> <div class="form-outline mb-3"> <input type="password" name="passwd" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" /> <label class="form-label" for="form3Example4">Password</label> <br> </div> <div class="d-flex justify-content-between align-items-center"> <!-- Checkbox --> <div class="form-check mb-0"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" /> <label class="form-check-label" for="form2Example3">Remember me</label> </div> <a href="#!" class="text-body">Forgot password?</a> </div> <div class="text-center text-lg-start mt-4 pt-2"> <button type="submit" class="btn btn-primary btn-lg" style="padding-left: 2.5rem; padding-right: 2.5rem;">Login</button> </div> <!-- 错误提示容器 --> <div id="errorTip" class="text-danger mt-3" style="display:none"></div> </form>
2.2 添加JS逻辑
在页面末尾添加如下JS代码即可实现表单异步提交、错误捕获:
// 监听表单提交事件 document.getElementById('loginForm').addEventListener('submit', async function(e) { // 阻止表单默认跳转提交行为 e.preventDefault(); const errorTip = document.getElementById('errorTip'); errorTip.style.display = 'none'; try { // 构造表单数据 const formData = new FormData(this); // 提交请求 const response = await fetch(this.action, { method: this.method, body: formData }); if (response.ok) { // 校验成功,直接用返回的HTML替换当前页面(和原表单提交逻辑完全一致) const html = await response.text(); document.open(); document.write(html); document.close(); } else if (response.status === 401) { // 账号密码错误,显示提示 const res = await response.json(); errorTip.textContent = res.message || '用户名或密码错误,请重试'; errorTip.style.display = 'block'; } else { // 其他服务端错误 errorTip.textContent = '服务端异常,请稍后重试'; errorTip.style.display = 'block'; } } catch (err) { // 如果没有修改后端,校验失败返回500会进入该分支 errorTip.textContent = '用户名或密码错误,请重试'; errorTip.style.display = 'block'; } })
说明
如果暂时无法修改CGIDEV2的后端代码,直接使用上面的前端代码即可捕获500错误,给用户显示账号密码错误的提示,不需要调整后端逻辑也能实现需求。
内容的提问来源于stack exchange,提问作者Rishab Kaushik
相关产品推荐
相关产品推荐

