$.ajax({
//这里是以键值对的形式,key的值不能乱写
type : "POST",
url : "${pageContext.request.contextPath}/servlet/UserServlet",
data : {"username":username},//必须是以json格式的数据
success:function(backData){
$("span").text(backData);
}
});
这里以检查注册用户名是否存在为例
jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>检查注册用户名是否存在</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script></head>
<body>
<!-- 在异步提交的方式下,form标签的action和method属性没有意义 -->
<form>
用户名:<input id="usernameID" type="text" name="username">
<input type="button" value="检查">
</form>
<span></span>
<script type="text/javascript">
$(":button").click(function(){
var username = $("#usernameID").val();
$.ajax({
//这里是以键值对的形式,key的值不能乱写
type : "POST",
url : "${pageContext.request.contextPath}/servlet/UserServlet",
data : {"username":username},//必须是以json格式的数据
success:function(backData){
$("span").text(backData);
}
});
});
</script>
</body>
</html>
servlet
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String tip = "";
if("哈哈".equals(username)){
tip = "已存在";
}else{
tip = "可用";
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
}
}