1. 程式人生 > >ssm學習總結-Ajax實現簡單的登入校驗

ssm學習總結-Ajax實現簡單的登入校驗

Mapper.java

publicAdmin login(Admin admin);

Mapper.xml

<selectid="login" parameterType="com.neusoft.pojo.Admin" resultType="com.neusoft.pojo.Admin">

        SELECT * from admin  where uname =#{uname} and pwd = #{pwd}

</select>

Service

public Admin login(Admin admin );

serviceimpl

public Admin login(Admin admin) {

       return adminMapper.login(admin);

   }

Controller

private  Admin admin;

@RequestMapping("/login")

public @ResponseBody  Admin login(String uname,String pwd){

//與json中Data中的名稱相對(可以嘗試直接傳入物件)

        admin = new Admin();

        admin.setUname(uname);

        admin.setPwd(pwd);

        admin = adminService.login(admin);

        return admin;

}

Js

//注意js的版本(寫三個等號在後期可以避免一些錯誤)

<scripttype="text/javascript" src="js/jquery-1.8.3.min.js"></script>

<scripttype="text/javascript">

//可以將方法繫結在指定的按鈕

       function requestJson(){

            var name =$("#uname").val();

            var pwd =$("#pwd").val();

           if(name===

""){

                alert("使用者名稱不能為空!");

                return false;

            }

            else if(pwd===""){

                alert("密碼不能為空!");

                return false;

            }

            else

            {

            $.ajax({

                type:'post',

                url:'login',

                dataType:"json",//注意使用的是打他dataType,而不是Content-Type

                async: true,

                data:{uname:name,pwd:pwd},

                success:function(data){

                   if(data===null){

                       alert("沒有這個使用者!")

                   }

                   else{

                       alert("登入成功")

                       window.location.href ="index.jsp";

                   }

                }

            });

           }

       }

   </script>

Html

<table>

   <tr>

       <td>使用者名稱:</td>

       <td><input type="text"  id="uname"></td>

   </tr>

   <tr>

       <td>密碼:</td>

       <td>

            <input type="password"id="pwd">

       </td>

   </tr>

   <tr><td colspan="2">

       <input type="submit" value="登陸"id="btn" onclick="requestJson()">

   </td></tr>

</table>