日期:2014-05-16  浏览次数:20713 次

(Ajax) Ajax的运行轨迹

?一段Ajax的代码

?

  function checkUser(){
   // Create xmlhttp object
  	var xmlhttp;
  			try{
			xmlhttp=new XMLHttpRequest();
		}catch(e){
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
  		
  		xmlhttp.onreadystatechange=function(){
  				if(4==xmlhttp.readyState){
  				alert('----');
  					if(200==xmlhttp.status){
  					// Get "data" which send back from Server..
  						var message= xmlhttp.responseText;
  						alert(message);
  						if(message=="unique"){
  							alert("Username is available!");
  						}else{
  							alert("Username is inavailable!");
  						}
  					}else{
  						alert(" Oops...Inner occur");
  					}
  				 }
  				}
  				
  					xmlhttp.open("post", "LoginServlet", true);
  					//Send Ajax Request to servlet
  					xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
  					var paras = "usermane="+document.getElementById("ID").value;
  					alert(paras);
  					//Send Ajax with paras to Server
  					xmlhttp.send(paras);
  }

?

?第一部分:从页面获取数据直接传到servlet

	xmlhttp.open("post", "LoginServlet", true);
  					//Send Ajax Request to servlet
  					xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
  					var paras = "usermane="+document.getElementById("ID").value;
  					alert(paras);
  					//Send Ajax with paras to Server
  					xmlhttp.send(paras);

?

第二部分:从servlet中获取数据传到页面上

xmlhttp.onreadystatechange=function(){
  				if(4==xmlhttp.readyState){
  				alert('----');
  					if(200==xmlhttp.status){
  					// Get "data" which send back from Server..
  						var message= xmlhttp.responseText;
  						alert(message);
  						if(message=="unique"){
  							alert("Username is available!");
  						}else{
  							alert("Username is inavailable!");
  						}
  					}else{
  						alert(" Oops...Inner occur");
  					}
  				 }
  				}

第三部分:servlet的代码:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		String usermane=request.getParameter("usermane");
		System.out.println(usermane);
		String res="";
		if(usermane.equals("justin")){
			res="occupied";
		}else{
			res="unique";
		}
		out.print(res);

}
}

?运行的轨迹如下:



?

?