1. Ajax is what

Asynchronous Javascript And XML

Not a new technology, but a combination of existing technologies:

  • 1. Use CSS and XHTML.
  • 2. Use the DOM model for interaction and dynamic display.
  • 3. Use XMLHttpRequest to communicate asynchronously with the server.
  • 4. Use javascript to bind and call.

2. What does Ajax do

Page if you want to refresh the local content. Then you need to reload the entire page. The user experience is not great (e.g., when we submit a form). This is to solve the problem of partial refresh. Leave everything else untouched and refresh only certain areas.

3. Internal principles

As we said earlier, Ajax is not a new technology. It’s about packaging existing technologies and using them to get the job done.

So now give you an example, or we judge whether the user name has been registered as an example.

Traditional way:

1. Enter a user name. 2. 3. Submit the data to the server. 4. 5. We prompt the user on the browser and give the resultCopy the code

The Ajax way:

The Ajax approach is the same as the previous approach in terms of what you want to do. Ajax also doesn’t help you know if your username is already in use without having to visit the server. So how does it work?

    1. Document.getelementbyid (“username”).value
    1. Perform the request with XmlHttpRequest. XmlHttpRequest is essentially a combination of XML, HTTP, and Request.
    1. At the end of the request, the result is received, and then use JS to complete the prompt.
    1. You can use CSS styles to increase the effect of the prompt.

Use 4.

This is all conceptual, you just need to know what Ajax does and there are two ways to submit data:

4.1 get way

To summarize the following code (which is explained in detail by the comments) : There are three steps:

  • 1. Create the XmlHttpRequest object. The object created in this part needs to be determined for different browsers, so you do not need to write it directly.
  • 2. Send the request Note: The Request object is obtained using the XmlHttpRequest in step 1. request.open(“GET”,”/AjaxAndJQuery/demoServlet01? name=’eric’&password=’123′”,true); request.send();
  • 3. Respond to the data sent by the server
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"% > <! DOCTYPE html PUBLIC"- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript"> // Create an XmlHttpRequest objectfunction  ajaxFunction(){
	   var xmlHttp;
	   try{ // Firefox, Opera 8.0+, Safari
	        xmlHttp=new XMLHttpRequest();
	    }
	    catch (e){
		   try{// Internet Explorer
		         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		      }
		    catch (e){
		      try{
		         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		      }
		      catch (e){}
		      }
	    }
		returnxmlHttp; } // Get the contents of the server response while sending the requestfunction getVar request=ajaxFunction(); Parameter 1: request type GET or POST Parameter 2: request path parameter 3: Whether asynchronous,true  or false
		*/
		// request.open("GET"."/AjaxAndJQuery/demoServlet01".true); // Go to request server request.open("GET"."/AjaxAndJQuery/demoServlet01? name='eric'&password='123'".true); request.send(); / / 3. Response to data should be sent to the server / * registered monitoring means, is a bit like to register a listener, changed a while to prepare Then perform = the right method * / request in the onreadystatechange =function() {
			//前半段表示readyState==4求已完成,且响应已就绪
			//status==200
		  if(request.readyState==4 && request.status==200) {// Alert (request.responseText); } } } </script> </head> <body> <a href="" onclick="get()">Ajax sends data via Get </a> </body> </ HTML >Copy the code

4.1 post way

A Post request is similar to a Get request, except that the data transfer method is different. The Get mode is concatenated directly after the address. But Post is sent through the send method. A request header is also set.

As above, summarize the following code:

  • 1. Create an XmlHttpRequest object
  • 2. Send the request does not carry data: request. Open (” POST “, “/ AjaxAndJQuery/demoServlet01″, true); request.send(); Carry data: request. Open (” POST “, “/ AjaxAndJQuery/demoServlet01”, true); request.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”); request.send(“name=eric&password=123456”);
  • 3. Receive data
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"% > <! DOCTYPE html PUBLIC"- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript"> // Create an XmlHttpRequest objectfunction  ajaxFunction(){
   var xmlHttp;
   try{ // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e){
	   try{// Internet Explorer
	         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	      }
	    catch (e){
	      try{
	         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	      }
	      catch (e){}
	      }
    }
	return xmlHttp;
 }
	function PostVar request=ajaxFunction(); //2. Send data request.open("POST"."/AjaxAndJQuery/demoServlet01".true); //request.send(); // Note: what if I need to take a parameter request? Request. SetRequestHeader (request. SetRequestHeader ("Content-type"."application/x-www-form-urlencoded"); Request. Send (); // If you are using POST with data, add the request header and specify that the submitted data type is a URL-encoded form."name=eric&password=123456"); / / 3. Receiving data / * registered monitoring means, is a bit like to register a listener, a moment to state has changed Then perform = the right method * / request in the onreadystatechange =function() {
			//前半段表示readyState==4求已完成,且响应已就绪
			//status==200
		  if(request.readyState==4 && request.status==200) {// Alert (request.responseText); } } } </script> <title>Insert title here</title> </head> <body> <a href="" onclick="Post()">Ajax sends data via Post </a> </body> </ HTML >Copy the code

4.2 Obtaining a Response from the Server

Once both Get and Post are basically used, you should think about getting the data. Before we have been very selfless to the server to submit data, so the server returned those data, how do we get through Ajax? This relies on the XMLHttprequest event onReadyStatechange, which listens for the status of the request, such as success or failure. If successful, the responseText or responseXML property of xmlHttprequest is used to retrieve the data

/ * registered monitoring means, is a bit like to register a listener, a moment to state has changed Then perform = the right method * / request in the onreadystatechange =function() {
			//前半段表示readyState==4求已完成,且响应已就绪
			//status==200
		  if(request.readyState==4 && request.status==200) {// Alert (request.responseText); }}Copy the code

Example: Verify the user name

Requirement: on the login page, when I enter a user name, I can go to the database to determine whether the user name exists.

Go straight to the code… The Controller class

protected void doThrows ServletException, IOException {// Get(HttpServletRequest Request, HttpServletResponse Response) throws ServletException, IOException { Call the persistence layer method, the transmission of return results to the presentation layer request. SetCharacterEncoding ("UTF-8"); // Set the encoding to re-encode the client request. String username = request.getParameter("username"); userDao dao = new userDaoImpl(); System.out.println(username); try { Long result = dao.getUserName(username); response.getWriter().println(result); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Copy the code

The front page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"% > <! DOCTYPE html PUBLIC"- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript"> // Create an XmlHttpRequest objectfunction  ajaxFunction(){
	   var xmlHttp;
	   try{ // Firefox, Opera 8.0+, Safari
	        xmlHttp=new XMLHttpRequest();
	    }
	    catch (e){
		   try{// Internet Explorer
		         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		      }
		    catch (e){
		      try{
		         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		      }
		      catch (e){}
		      }
	    }
		return xmlHttp;
	 }
	function checkUserNameVar request=new ajaxFunction(); Var name= document.getelementById ("name").value; //2. Send message /* Tried to get mode, but failed String STR ="/AjaxAndJQuery/userServlet? username="+"'"+name+"'";
		alert(str);
		request.open("GET",str,true);
		request.send(); */
		request.open("POST"."/AjaxAndJQuery/userServlet".true); // Note: what if I need to take a parameter request? Request. SetRequestHeader (request. SetRequestHeader ("Content-type"."application/x-www-form-urlencoded"); Request. Send (); // If you are using POST with data, add the request header and specify that the submitted data type is a URL-encoded form."username="+name); / / 3. Receiving data / * registered monitoring means, is a bit like to register a listener, a moment to state has changed Then perform = the right method * / request in the onreadystatechange =function() {
			//前半段表示readyState==4求已完成,且响应已就绪
			//status==200
		  if(request.readyState==4 && request.status==200) {// Display response information //alert(request.responseText); var result=request.responseText;if(result==1){
				   document.getElementById("span01").innerHTML=" The username already exists ";
			   }else{
				   document.getElementById("span01").innerHTML= ";
			   }
		    }
		  }

	}
</script>
<title>Insert title here</title>
</head>
<body>
<table border="1" width="500">< tr> < TD > Username :</ TD >< TD ><inputtype="text" name="name" id="name"  onblur="checkUserName()"><span id="span01"></span></td> </tr> <td> Password </ TD >< TD ><inputtype="text" name=""></td> </tr> <td> mailbox </ TD >< TD ><inputtype="text" name=""></td> </tr> <td>< td><inputtype="text" name=""></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="Registered"></td>
		</tr>
	</table>
</body>
</html>
Copy the code