用Ajax請求后台數據


我們先不講ajax的原理,還是先以實戰為主,看一下這個東西到底怎么用的?

form表單:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div
		style="width: 300px; padding: 20px; margin: 20px; border: 4px dashed #ccc;">
		<form id="myform" name="myform" method="post" action="#">
			<table>
				<tr>
					<td>用戶名:</td>
					<td><input type="text" id="username" name="username" placeholder="請輸入用戶名"
						onfocus="this.placeholder=''" onblur="this.placeholder='請輸入用戶名'" /></td>
				</tr>
				<tr>
					<td>密碼:</td>
					<td><input type="password" id="password" name="password" placeholder="請輸入密碼"
						onfocus="this.placeholder=''" onblur="this.placeholder='請輸入密碼'" /></td>
				</tr>
				<tr>
					<td colspan="2"><input type="button" value="提交"
						onclick="doLogin('weixin');" /></td>
				</tr>
			</table>
			<input type="hidden" name="loginType" id="loginType" value="weixin" />
		</form>
		
	</div>
	<div id="errMsg" style="color: red">${errMsg}</div>
	<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
	<script type="text/javascript">
		function doLogin(type) {
			$.ajax({
				type : "GET",
				url : "login.do",
				data : {
					username : $("#username").val(),
					password : $("#password").val(),
					type : type
				},
				dataType : "json", //預期服務器返回的數據
				success : function(data) {
					if (data.errCode < 0) {
						alert("登錄失敗!")
						$("#errMsg").show().html(data.errMsg).stop(true, true)
								.fadeOut(3000);
					} else {
						//登錄成功,做其他處理
						alert("恭喜你,登錄成功!");
					}
				}
			});
		}
	</script>
</body>
</html>

  

LoginServlet

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("用戶登錄...");
		System.out.println("開始存入map...");
		Map<String,Object> map=StringUtils.getParameters(req);
		System.out.println("存入map成功!");
		System.out.println(map);
		
		if(StringUtils.isEmpty(map.get("username"))){
			StringUtils.writeObject(resp, "{\"errCode\":-1,\"errMsg\":\"用戶名不能為空!\"}");
			System.out.println("用戶名不能為空!");
			return;
		}
		if(StringUtils.isEmpty(map.get("password"))){
			StringUtils.writeObject(resp,"{\"errCode\":-2,\"errMsg\":\"密碼不能為空!\"}");
			System.out.println("密碼不能為空!");
			return;
		}
		System.out.println("登陸成功!");
		StringUtils.writeObject(resp,"{\"errCode\":0,\"errMsg\":\"登錄成功!\"}");
	}

  

頁面效果:

 

參考:https://www.cnblogs.com/skyblue-li/p/8251234.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM