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

使用Ajax入门
Js: 
<script type="text/javascript">
  var xmlHttpRequest;
  //创建XMLHttpRequest对象
  function createXMLHttpRequest()
  {
  if(xmlHttpRequest == null)
  {
  //对于 Mozila 浏览器
  if(window.XMLHttpRequest)
  {
  xmlHttpRequest = new XMLHttpRequest();
  }
  //对于 IE 浏览器
  else if(window.ActiveXObject)
  {
  try
  {
  xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch(e)
  {
  try
  {
  xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch(e)
  {
 
  }
  }
  }
  }
  }
  //发送请求
  function sendRequest()
  {
  var name = document.getElementById("name");
  var pass = document.getElementById("pass");
  var nameValue = name.value;
  var passValue = pass.value;
  createXMLHttpRequest();
  var url = "LoginServlet";
  xmlHttpRequest.open("POST", url, true);
  xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  xmlHttpRequest.onreadystatechange = processResponse;
  xmlHttpRequest.send("name="+nameValue+"&pass="+passValue);
  }
  //处理服务器响应
  function processResponse()
  {
  if(xmlHttpRequest.readyState == 4)
  {
  if(xmlHttpRequest.status == 200)
  {
  document.getElementById("msg").innerHTML = xmlHttpRequest.responseText;
  }
  }
  }
  function check()
  {
  var name = document.getElementById("name");
  var pass = document.getElementById("pass");
  var nameValue = name.value;
  var passValue = pass.value;
  var msg = "";
  if(nameValue == null || nameValue == "")
  {
  msg += "用户名为空 \n";
  }
  if(passValue == null || passValue == "")
  {
  msg += "密码为空 \n";
  }
  if(msg == null || msg == "")
  {
  sendRequest();
  }
  else
  {
  document.getElementById("msg").innerHTML = msg;
  }
  }
  </script>

Servlet:
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
if (name == null || pass == null) {
PrintWriter out = response.getWriter();
out.println("用户名和密码都不能为空");
}
if(ChatService.instance().validLogin(name, pass)){
forward("/chat.jsp",request,response);
}else{
PrintWriter out = response.getWriter();
out.println("用户名或密码错误");
}
}

private void forward(String url, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletConfig().getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);
}