Ajax sends a Post request and ajax sends a post request.
THE post request sent by Ajax is similar to the get request. The following describes the specific instance and the JSP display page:
<Form action = "servlet/LoginServlet" method = "post"> <table> <tr> <td> User Account: </td> <input type = "text" name = "username" onblur = "checkUser (this) "/> </td> </tr> <td> User Password: </td> <input type = "password" name = "password"/> </td> </tr> <td> <input type =" submit "value =" register "/> </td> <input type =" reset "value =" reset "> </td> </tr> </table> </form>
Then let's look at the Servlet class that processes the sent information. Because it is POST-based, let's take a look at the doPost method.
@Overrideprotected 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);elseout.print(true);out.flush();out.close();}
Then, let's see how javascript implements Ajax requests.
<Script type = "text/javascript"> // create XMLHttpRequestfunction createXmlHttpRequest () {if (window. XMLHttpRequest) {return new XMLHttpRequest ();} else {return new ActiveXObject ("Microsoft. XMLHTTP ") ;}}// call the function checkUser (obj) method when the user account input box loses focus {// obtain the value var user = obj. value; // if the value in the input box is null, a window is displayed, and the input box is given the focus if (! User) {alert ("the user name cannot be blank! "); Obj. focus (); return;} // when it is not empty, use Ajax requests to send information to the background, verify whether the user name is available // post request string var url = "servlet/LoginServlet"; // request parameter var userinfo = "username =" + user; // call the method to create the XMLHttpRequest object XmlHttpRequest = createXmlHttpRequest (); // set the callback function XmlHttpRequest. onreadystatechange = finish; // initialize xmlhttprequestXmlHttpRequest. open ("POST", url, true); XmlHttpRequest. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); // send the request XmlHtt PRequest. send (userinfo);} // callback function finish () {if (XmlHttpRequest. readyState = 4 & XmlHttpRequest. status = 200) {var result = XmlHttpRequest. responseText; alert (result); if (result = "true") {alert ("username available! ");} Else {alert (" the user name is unavailable! ") ;}}</Script>