表單提交時如何將錯誤資訊傳遞到頁面中,並且儲存原來提交資料

來源:互聯網
上載者:User

標籤:style   java   os   io   資料   for   ar   問題   

曾經何時,你還有我或許都在困惑,如何方便的將驗證不通過的表單資訊再返回到前台頁面,例如我註冊一個帳號,辛辛苦苦填寫了N多項,一個格式驗證沒有通過,一切都需要充填,雖然Ajax可以解決這個問題,但是我們總不能把所有表單提交都弄成ajax,更何況有若干人就是沒事把javascript給禁止了。哎哎,好瞭解決方案來了,下面以使用者登入狀態例,說說我的解決方案。

伺服器端用nodejs實現:

login.html 簡單的提交表單

<form action=""  id="loginForm" method="post"><!--如果提交的資訊由使用者資訊將使用者資訊填充到表單中--><label>手機:</label><input type="text"  class="wk_table_input" name="user[mobile]" placeholder="手機號" id="mobile" value="<%if(user){%><%=user.mobile%><%}%>"/><br/><label>密碼:</label><input type="password"  class="wk_table_input" name="user[pwd]" placeholder="密碼" id="pwd" value="<%if(user){%><%=user.pwd%><%}%>"/><br/><input type="submit" placeholder=" 登入" class="workteam_public_submit"style="background: #69b754;"></form> <!--如果有錯,顯示後端返回的錯誤--> <%if(locals.error){%><td class="wpt_td2"><%=error%><%}%>

 

 

function login(req, res, next) {    //如果使用者提交了資訊,將資訊返回到前端頁面    var user = req.body.user;    res.render("login", {title:‘使用者登入‘, user:user });};
function loginAction(req, res, next) {    var user = req.body.user;    if(!user || !user.mobile || !user.pwd) {        if (req.xhr) {            res.json({ret:-1, errMsg:‘手機號或密碼不可為空‘});        } else {            res.locals.error = ‘手機號或密碼不可為空‘;            login(req, res, next);        }    } else {         if (user.mobile === ‘12345678901‘ && user.pwd === ‘123456‘){            if (req.xhr){                res.json({ret:0,errMsg:"",backUrl:""});            } else {                res.redirect("/home");            }        } else {            //將錯誤資訊放到locals中,然後調用視圖函數            res.locals.error = "使用者名稱或密碼錯誤";            login(req, res, next);        }    }    });

?            res.locals.error = ‘手機號或密碼不可為空‘; 


            login(req, res, next);

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.