Ajax--->初体验
前期工作以及注意事项
下载Jquery,放在web目录下,导入到本地中
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
注意:路径问题、<script>不是自结束标签
1、index.jsp
jsp注意事项:取值# data:{'name':$("#name").val()},
Ajax:在方法内部嵌套ajax 使用 $.post({ })
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script> <script> function a1(){ $.post({ //跳转到对应的controller url:"${pageContext.request.contextPath}/a3", //携带的数据 //取值注意$(#name)取对应的值,设置同理 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()" /> <span id="userInfo"></span> </p> <p> 密码:<input type="text" id="pwd" onblur="a2()"/> <span id="pwdInfo"></span> </p> </body> </html>
2、对应的controller
踩坑(返回JSON字符串加@ResponseBody)
不然去找msg.jsp页面,找不到返回404
@RequestMapping("/a3") @ResponseBody public String a3(String name,String pwd){ String msg = ""; //模拟数据库中存在数据 if (name!=null){ if ("admin".equals(name)){ msg = "OK"; }else { msg = "error"; } } if (pwd!=null){ if ("123456".equals(pwd)){ msg = "OK"; }else { msg = "error"; } } return msg; //由于@RestController注解,将msg转成json格式返回 }