Key steps:
1 creating XMLHttpRequest objects;
2 adding a callback function;
3 Creating links;
4 Set the request header information;
5 sending data;
var xmlhttprequest;function Chaj () {if (f1.name.value==null| | f1.name.value== "") {alert ("cannot be empty"); return false;} if (window. XMLHttpRequest) {xmlhttprequest=new XMLHttpRequest ();} Else{xmlhttprequest=new ActiveXObject ("Microsoft.XMLHTTP");} Xmlhttprequest.onreadystatechange=callback;var url= "My"; Xmlhttprequest.open ("Post", url,true); Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); XmlHttpRequest.send ("Name= "+f1.name.value+" ×tamp= "+ (new Date ()). GetTime ()); function CallBack () {if (xmlhttprequest.readystate==4 && xmlhttprequest.status==200) {var result= Xmlhttprequest.responsetext;result=result.replace (/(^\s*) | ( \s*$)/g, ""); alert (result);//alert (result);}}
Note: Xmlhttpservlet is a global variable, do not forget to set Requestheadder information before sending data.
Server-side:
return information via PrintWriter;
protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); String name1=request.getparameter ("name"); String timestamp1=request.getparameter ("TimeStamp"); System.out.println (NAME1+TIMESTAMP1); PrintWriter out=response.getwriter (); Out.print ("Success"); Out.flush (); Out.close ();}
JavaScript for Ajax