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

Ajax简单应用过程
1 jsp或html页面中调用js写的方法
<script type="text/javascript">
    var xmlHttp;
   
    function createXMLHttpRequest()
    {
      if(window.ActiveXObject)
      { 
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      else if(window.XMLHttpRequest)
      {
        xmlHttp = new XMLHttpRequest();
      }
    }
    
    function checkn()
    {
      createXMLHttpRequest();
      xmlHttp.onreadystatechange = processor;
      xmlHttp.open("GET","CheckUser");
      xmlHttp.send(null);
    }
    
    function processor()
    {
      var result;
      if(xmlHttp.readyState == 4)
      {
        if(xmlHttp.status == 200)
        {
          result = xmlHttp.responseText;//这是接收文本,还有接收xml的
          document.getElementById("test").value = result;
        }
      }
    }
  </script>

2 实现servlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("gb2312");

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

		response.setContentType("text/html");//另一种是text/xml
		PrintWriter out = response.getWriter();
		String result = "宁夏";
		out.println(result);
		out.flush();
		out.close();
	}


3 在web.xml中配置servlet