AJAX submit method (POST) Demon, ajax submit postdemon
The POST submission method of AJAX is essentially similar to GET. There are some minor differences. When the POST is to submit data, the setRequestHeader () method is required to submit the HTTP header, and then send () method (Format :"? Str = String & str2 = String2 "); str and str2 are variable names, and String and String2 are the values to be sent.
Others are similar to Get.
The following is a demon that sends and receives usernameand password. first, create a. html file with a random name. The Code is as follows:
<Body> <script type = "text/javascript" src = "1.js"> </script> User Name: <input type = "text" id = "username"/> <br/> User Password: <input type = "password" id = "password"/> <br/> <input type = "button" onclick = "fun (); "value =" Submit "> <br/> <p id =" txt "> </p> </body>
Connect to create the Javascript file for 1.js. To be in the same directory as .html, the Code is as follows:
Function fun () {if (window. XMLHttpRequest) {xmlhttp = new XMLHttpRequest ();} else if (window. activeXObject) {xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP ");} else {alert (" the object cannot be built ");} username = document. getElementById ("username "). value; password = document. getElementById ("password "). value; xmlhttp. onreadystatechange = handchange; xmlhttp. open ("POST", "Servlet1? Username = "+ username +" & password = "+ password, true); xmlhttp. setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); // sets the HTTP header xmlhttp. send ("task = task & msg = msg"); // This is only to prove the use of send (), meaningless} function handchange () {if (xmlhttp. readyState = 4) {if (xmlhttp. status = 200) {document. getElementById ("txt "). innerHTML = xmlhttp. responseText ;}} else {document. getElementById ("txt "). innerHTML = "wait patiently... ";}}
Create a Servlet. Note that the web ing name in web. xml must be the same as xmlhttp. open ("POST", "Servlet1? Username = "+ username +" & password = "+ password, true); The Servlet1 here is consistent.
The doPost code for Servlet1 is as follows:
Response. setContentType ("text/html"); response. setCharacterEncoding ("UTF-8"); PrintWriter out = response. getWriter (); String username = new String (request. getParameter ("username "). getBytes ("ISO-8859-1"), "UTF-8"); String password = new String (request. getParameter ("password "). getBytes ("ISO-8859-1"), "UTF-8"); String task = new String (request. getParameter ("task "). getBytes ("ISO-8859-1"), "UTF-8"); String msg = new String (request. getParameter ("msg "). getBytes ("ISO-8859-1"), "UTF-8"); System. out. println (username + "" + password); if (task. equals ("task") {if (msg. equals ("msg") {out. println (username + "" + password); // send(if data is successfully transferred, the input value is displayed in .html }}
As follows:
Enter data and click submit as follows: