Ajax
Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)
1、有什么用?
简单来说,就是不需要刷新网页也可以做到局部网页更新的效果.
例如:网站给你推送了一条消息,你的消息那里会多一个红点,这就是使用ajax来做的,局部网页更新(不需要刷新)
2、该如何用?
动态验证输入框内容
输入框中输入admin 显示,正确,输入其他显示其他
前端
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<script src="js/jquery-3.6.0.js"></script>
<h2>Hello World!</h2>
<input type="text" name="password" id="password">
<span style="color: red"></span>
</body>
<script>
let password = $("#password");
password.on("blur",function(){
$.ajax({
type:"GET",
url:"user.do",
data:{method:"pwdmodify",password:password.val()},
dataType:"json",
success:function(data){
if(data.result == "admin"){//旧密码正确
validateTip(password.next(),{"color":"green"},"yes",true);
}else if(data.result == "haha"){//旧密码输入不正确
validateTip(password.next(),{"color":"red"},"haha" ,false);
}else if(data.result == "xixi"){//当前用户session过期,请重新登录
validateTip(password.next(),{"color":"red"},"xixi",false);
}else{
validateTip(password.next(),{"color":"red"},"不认识",false);
}
},
error:function(data){
//请求出错
console.log(data);
validateTip(password.next(),{"color":"red"},"imgNo" + " 请求错误",false);
}
});
})
function validateTip(element,css,tipString,status){
element.css(css);
element.html(tipString);
element.prev().attr("validateStatus",status);
}
</script>
</html>
public class Test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
String password = req.getParameter("password");
System.out.println(password);
HashMap<String, String> resultMap = new HashMap<String, String>();
// 这里的数据(admin,haha...)用数据库查出来的就可以了。
if("admin".equals(password)){
resultMap.put("result","admin");
}else if("haha".equals(password)){
resultMap.put("result","haha");
}else if("xixi".equals(password)){
resultMap.put("result","xixi");
}
resp.setContentType("application/json");
resp.getWriter().write(JSONArray.toJSONString(resultMap));
}
}
依赖
<!-- 转json https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
注册servlet
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/user.do</url-pattern>
</servlet-mapping>