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请求
"); 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>