No idle chatter, direct lecture.
Using the XMLHttpRequest object is divided into the following seven steps:
-
Creating objects
-
Set Expiration Time
-
Set data format
-
Initializing an HTTP request
-
Set HTTP Header Requests
-
Processing of postback data
-
Send HTTP Request
The corresponding code is shown below
<script type= "Text/javascript" > var xhr; Function goajax () {//1. Create Object Xhr = new xmlhttprequest ();if (window. XMLHttpRequest) { xhr = new xmlhttprequest ();} else if (window. ActiveXObject) { xhr = new activexobject ("Microsoft.XMLHTTP");} 2. Set expiration time XHR.SETTIMEOUT&NBSP;=&NBSP;3000;//3. Format Data xhr.responsetype = "text";//4. Initialize http Request parameters (not sent) Xhr.open ("POST", "Servlet/ajaxloginservlet", true)//5. Set HTTP request Xhr.setrequestheader (" Content-type ", " application/x-www-form-urlencoded ");//6. Processing of postback data//registration related event callback handler function//6.1 After the postback data has been loaded, execute Xhr.onload = function (e) { //alert (this.readystate + "| |" + this.status); if (this.readystate == 4 | | &NBSP;THIS.STATUS&NBSP;==&NBSP;200) {var div = document.getelementbyid ("Divcontent");d iv.innerhtml = this.responsetext; }};//6.2 Access Error xhr.onerror = function (e) { alert ("Login failed! ");};/ /6.3 Timeout//xhr.ontimeout = function (e) {//};//6.4 status change/* xhr.onreadystatechange = Function (e) { if (this.readystate == 4 | | &NBSP;THIS.STATUS&NBSP;==&NBSP;200) { alert (This.responsetext); }} *///7. Sending Data var Username = document.getelementbyid ("username") .value;var pwd = document.getElementById ("password"). Value;xhr.send ("username=" + username + "&password = " + pwd); }</script>
The HTML page code looks like this:
<body> account: <input type= "text" name= "username" id= "username"/><br/> Password: <input type= "Password" n Ame= "password" id= "password"/><br/> <input type= "button" value= "Login" onclick= "Goajax ();"/> <div Id= "Divcontent" style= "width:200px; height:100px; " ></div></body>
The servlet file code is as follows:
public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Set content format Response.setcontenttype ("text/html"); PrintWriter out = Response.getwriter ();//Gets the user name and password in the URL string username = Request.getparameter ("username"); String Password = request.getparameter ("password");//Successful output success failed output FailIf ("haha". Equals (username) && "123" . Equals (password)) {out.println ("Success");} else {out.println ("fail");} Out.flush (); Out.close ();}
This article is from the "Software Thinking" blog, please be sure to keep this source http://softi.blog.51cto.com/13093971/1950888
Java from getting started to giving up: basic usage of XMLHttpRequest