The post submission method of Ajax, in essence, is similar to get, some small difference, post to submit data, the setRequestHeader () method is required to submit the HTTP header, and then the Send () method to submit data in the format: "? str=string &str2=string2 "), str and STR2 are variable names, and string and String2 are the values to send.
Others are similar to get.
Below is a demon that sends and receives username and password, first creating an. html file with the following code:
<Body> <Scripttype= "Text/javascript"src= "1.js"></Script>User name:<inputtype= "text"ID= "username" /><BR/>User password:<inputtype= "Password"ID= "Password" /><BR/> <inputtype= "button"onclick= "Fun ();" Value= "Commit "> <BR/> <PID= "txt"></P> </Body>
Next, create a 1.js JavaScript file, in the same directory as the. html, with the following code:
functionFun () {if(window. XMLHttpRequest) {XMLHTTP=NewXMLHttpRequest (); }Else if(window. ActiveXObject) {XMLHTTP=NewActiveXObject ("Microsoft.XMLHTTP"); }Else{alert ("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"); Here just to prove the use of send (), meaningless}functionHandchange () {if(Xmlhttp.readystate = = 4){ if(Xmlhttp.status = = 200) {document.getElementById ("TXT"). InnerHTML =Xmlhttp.responsetext; } }Else{document.getElementById ("TXT"). InnerHTML = "wait patiently ..."; }}
A servlet is created below to note the mapping name in Web. XML and xmlhttp.open ("POST", "Servlet1?username=" +username+ "&password=" + Password,true); The Servlet1 here are consistent.
The Servlet1,dopost code is as follows:
Response.setcontenttype ("text/html"); Response.setcharacterencoding ("UTF-8"); PrintWriter out=Response.getwriter (); String username=NewString (Request.getparameter ("username"). GetBytes ("Iso-8859-1"), "UTF-8"); String Password=NewString (Request.getparameter ("password"). GetBytes ("Iso-8859-1"), "UTF-8"); String Task=NewString (Request.getparameter ("task"). GetBytes ("Iso-8859-1"), "UTF-8"); String msg=NewString (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 the data is successfully passed in, the input value is displayed in the. html also polygon}}
As follows:
Enter the data, click Submit, as follows:
Ajax Submission Method (POST) Demon