Ajax通过post方法向Servlet提交信息

jsp文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>	
<body>
	<table id="table">
	<tr>
	<th>ID</th>
	<th>账户</th>
	<th>密码</th>
	</tr>
<tbody id="tbody">
</tbody>
</table>
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
	var id=34;
	var name="张三";
	$.ajax({
		  type: 'POST',
		  url: 'TestJosnServlet',
		  data: {"id":id,"name":name},
		  dataType:"JSON",
		  success: function(result,msg){
			//alert(msg);
			//alert(dat.dataa);
			show(result.data);
			
		  },
		  error:function(xhr,errorMsg,error){
			  alert(xhr.status);
			  alert(errorMsg);//console.log();
		  }
		});
});
function show(data){
	var html="";
	console.log(data);
	for (var d of data){
		html += "<tr><td>"+d['id']+"</td><td>"+d['username']+"</td><td>"+d['password']+"</td></tr>";
		alert(html);
	}
	$("#tbody").empty().html(html);
}
</script>
</html>

servlet文件

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
	       response.setCharacterEncoding("UTF-8");
		String id =request.getParameter("id");
		String name =request.getParameter("name");
		System.err.println(id);
		System.err.println(name);
		String sql ="select*from user";
		List<Map<String,String>> show = mysqlUtil.show(sql, new String[] {"id","username","password"});
		String json="{\"code\":\"200\",\"data\":[";
		for(Map<String,String> map:show) {
			String idstr=map.get("id");
			String username=map.get("username");
			String password=map.get("password");			
//			json+="{";
//			for(String key:map.keySet()) {
//				json+="\""+key+"\":\""+map.keySet()+"\",";
//			}
//			json=json.substring(0,json.length()-1);
//			json+="},";
			json+="{\"id\":\""+idstr+"\",";
			json+="\"username\":\""+username+"\",";
			json+="\"password\":\""+password+"\"},";
		}	
		//String json ="{\"code\":\"200\",\"data\":+"["+"{"+\"id\":"+map.get("id")+",\"username\":"+map.get("username")+",\"password\":"+map.get("password")+"}"+"]"}";
		json=json.substring(0, json.length()-1);
		json+="]}";
		response.getWriter().write(json);
		//request.getRequestDispatcher("list.jsp").forward(request, response);

猜你喜欢

转载自blog.csdn.net/weixin_43611712/article/details/90974796