Ajax发送post请求与发送get请求大致类似。以下看详细实例。首先看JSP显示页面:
<form action="servlet/LoginServlet" method="post">
<table>
<tr>
<td>用户账号:</td>
<td><input type="text" name="username" onblur="checkUser(this)"/></td>
</tr>
<tr>
<td>用户密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td><input type="submit" value="注冊"/></td>
<td><input type="reset" value="重置"></td>
</tr>
</table>
</form>
然后看对发送信息进行处理的Servlet类。由于是POST方式发送信息,所以看一下doPost方法。
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charaet=UTF-8");
PrintWriter out = response.getWriter();
String name=request.getParameter("username");
if(name.equals("admin"))
out.print(false);
else
out.print(true);
out.flush();
out.close();
}
然后看javascript怎样实现Ajax请求
<script type="text/javascript">
//创建XMLHttpRequest
function createXmlHttpRequest(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
//当用户账号输入框失去焦点时调用该方法
function checkUser(obj){
//获取输入框输入的值
var user = obj.value;
//假设输入框中的值为空。那么弹窗提示。而且让该输入框获得焦点
if(!user){
alert("username不能为空! ");
obj.focus();
return;
}
//不为空时。使用Ajax请求向后台发送信息,验证该username是否可用
//post请求字符串
var url="servlet/LoginServlet";
//请求參数
var userinfo = "username="+user;
//调用方法创建XMLHttpRequest对象
XmlHttpRequest = createXmlHttpRequest();
//设置回调函数
XmlHttpRequest.onreadystatechange=finish;
//初始化xmlhttprequest
XmlHttpRequest.open("POST",url,true);
XmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//发送请求
XmlHttpRequest.send(userinfo);
}
//回调函数
function finish(){
if(XmlHttpRequest.readyState == 4&& XmlHttpRequest.status == 200){
var result = XmlHttpRequest.responseText;
alert(result);
if(result =="true"){
alert("username可用!");
}else{
alert("username不可用!");
}
}
}
</script>