JQuery Ajax局部刷新功能
程序员文章站
2022-06-17 11:51:07
...
直接通过一个案例来说明一下Ajax和JQuery的基本用法吧,用户注册时,判断当前用户名是否可用,通过弹窗的形式来通知用户,如果用户起的名字为skh则不允许注册,否则可以,就不加数据库来测试了,太麻烦.....
Servlet:
package cn.skh.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AjaxServlet
*/
@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AjaxServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String test = request.getParameter("test");
PrintWriter out = response.getWriter();
if("skh".equals(test) ) {
out.print("false");
}else {
out.print("true");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
前端JSP:
tips:需要注意的就是$.ajax的格式,以及所需要的参数。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//给账号文本框绑定失去焦点的事件
$("#test").blur(function(){
var test=$("#test").val();
var msg1={
"test":test,
};
$.ajax({
url:"AjaxServlet",//设置服务器地址,即为servlet配置的url-pattern
type:"post",//提交的方式
data:msg1,//提交到服务器的数据,多个值以逗号分割开
datatype:"text",
success:function(msg){//回调函数,msg是返回的数据
if(msg=="false")
{
alert("flase");
}
else{
alert("true");
}
}
});
});
});
</script>
</head>
<body>
用户名:<input id="test" type="text" maxlength="20">
<br>
密码:<input type="text">
</body>
</html>
结果是没问题的,感兴趣的可以自己去验证一下,这里就不在贴图了。。。。
上一篇: Git与GitHub的简单了解(3)
下一篇: 农夫求医