Ajax之Jquery封装使用举例
1 <html> 2 <head> 3 <meta charset="UTF-8"> 4 <title>登陆页面</title> 5 <link rel='stylesheet prefetch' href='https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css'> 6 <link rel="stylesheet" href="css/style.css"> 7 <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> 8 9 <script type="text/javascript"> 10 function sub() { 11 var name = $("#name").val(); 12 var password = $("#password").val(); 13 //第二步:验证数据,这里需要从数据库调数据,我们就用到了ajax 14 $.ajax({ 15 url: "/submit",//请求地址 16 data: {name: name, password: password},//提交的数据 17 type: "POST",//提交的方式 18 dataType: "TEXT", //返回类型 TEXT字符串 JSON XML 19 success: function (data) { // 校验返回内容,进行跳转 20 //开始之前要去空格,用trim() 21 if (data.trim() == "true") { 22 window.location.href = "/welcome?name=" + name; 23 } 24 else { 25 alert("用户名或者密码错误!"); 26 } 27 }, 28 error: function (xhr) { 29 // 失败输出HTTP状态码 30 alert("调用失败!HTTP状态码:" + xhr.status); 31 } 32 }) 33 } 34 </script> 35 </head> 36 37 <body> 38 <div class="wrapper"> 39 <div class="form-signin"> 40 <h2 class="form-signin-heading">请登陆</h2> 41 <input type="text" class="form-control" value="tom" name="name" id="name" placeholder="用户名" required="" 42 autofocus=""/> 43 <input type="password" class="form-control" value="123" name="password" id="password" placeholder="密码" 44 required=""/> 45 <label class="checkbox"> 46 <input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe">记住我 47 <a href="infoSubmit.html" class="regsiter">注册</a> 48 </label> 49 <button type="submit" id="btn" class="btn btn-lg btn-primary btn-block" onclick="sub()">登陆</button> 50 </div> 51 </div> 52 </body> 53 54 </html>
style.css
1 body { 2 background: #eee !important; 3 } 4 5 .wrapper { 6 margin-top: 80px; 7 margin-bottom: 80px; 8 } 9 10 .form-signin { 11 max-width: 380px; 12 padding: 15px 35px 45px; 13 margin: 0 auto; 14 background-color: #fff; 15 border: 1px solid rgba(0, 0, 0, 0.1); 16 } 17 18 .form-signin .form-signin-heading, 19 .form-signin .checkbox { 20 margin-bottom: 30px; 21 } 22 23 .form-signin .checkbox { 24 font-weight: normal; 25 } 26 27 .form-signin .form-control { 28 position: relative; 29 font-size: 16px; 30 height: auto; 31 padding: 10px; 32 -webkit-box-sizing: border-box; 33 -moz-box-sizing: border-box; 34 box-sizing: border-box; 35 } 36 37 .form-signin .form-control:focus { 38 z-index: 2; 39 } 40 41 .form-signin input[type="text"] { 42 margin-bottom: -1px; 43 border-bottom-left-radius: 0; 44 border-bottom-right-radius: 0; 45 } 46 47 .form-signin input[type="password"] { 48 margin-bottom: 20px; 49 border-top-left-radius: 0; 50 border-top-right-radius: 0; 51 } 52 53 .checkbox { 54 margin-left: 100px; 55 } 56 57 .regsiter { 58 margin-left: 20px; 59 }
截图:
点击登陆按钮触发Ajax请求