一.前端拿取后端的传递结果
Java:
@RequestMapping("/a2") public List<User> a2(){ ArrayList<User> list = new ArrayList<User>(); list.add(new User(1,"msf","男")); list.add(new User(1,"ms","女")); list.add(new User(1,"m","男")); return list; }
前端拿取结果,通过Ajax:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>前端展示</title> <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.4.js"></script><%--script 引入资源文件,必需也是双标签,但标签会报错--%> <script> $(function () { $("#btn").click(function () { $.post("${pageContext.request.contextPath}/a2",function (data) { var html=""; for(let i=0;i<data.length;i++){ html+="<tr>"+ "<td>"+data[i].name+"</td>"+ "<td>"+data[i].sex+"</td>"+ "<td>"+data[i].age+"</td>" +"</tr>" } $("#content").html(html); }) }) }) </script> </head> <body> <input type="button" value="获取数据" id="btn"> <table> <tr> <td>姓名</td> <td>性别</td> <td>年龄</td> </tr> <tbody id="content"> <%-- 后端来给予数据 --%> </tbody> </table> </body> </html>
二.前端Ajax提示
Java代码:
@RequestMapping("/a3") public String a3(String name,String pwd){ String msg=""; if(name!=null){ if("msf".equals(name)){ msg="ok"; }else { msg="用户名有误"; } } if(pwd!=null){ if("123456".equals(pwd)){ msg="ok"; }else { msg = "密码有误"; } } return msg; }
前端:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Ajax</title> <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.4.js"></script><%--script 引入资源文件,必需也是双标签,但标签会报错--%> <script> function a1() { $.post({ url:"${pageContext.request.contextPath}/a3", data:{"name":$("#name").val()}, success:function(data){ if(data.toString()==='ok'){ $("#userInfo").css("color","green"); }else { $("#userInfo").css("color","red"); } $("#userInfo").html(data); } }) } function a2() { $.post({ url:"${pageContext.request.contextPath}/a3", data:{"pwd":$("#pwd").val()}, success:function (data) { if(data.toString()==='ok'){ $("#pwdInfo").css("color","green"); }else { $("#pwdInfo").css("color","red"); } $("#pwdInfo").html(data); } }) } </script> </head> <body> <p> 用户名:<input type="text" id="name" onblur="a1()" required> <span id="userInfo"></span> </p> <p> 密码:<input type="text" id="pwd" onblur="a2()" required> <span id="pwdInfo"></span> </p> </body> </html>
标签:function,name,Ajax,html,msg,data From: https://www.cnblogs.com/5ran2yl/p/17213222.html