一个简单的Ajax例子

今天写个Ajax的小例子,我在项目中并没有用到过Ajax,看到Ajax很流行,今天写个demo,希望大家指点

创建一个全局的XMLrequest对象,该对象的方法如下

open():建立到服务器的新请求。

send():向服务器发送请求。

abort():退出当前请求。

readyState:提供当前 HTML 的就绪状态。

responseText:服务器返回的请求响应文本。

Onreadystatechange属性的五种状态:

  • 0:请求没有发出(在调用 open() 之前)。
  • 1:请求已经建立但还没有发出(调用 send() 之前)。
  • 2:请求已经发出正在处理之中(这里通常可以从响应得到内容头部)。
  • 3:请求已经处理,响应中通常有部分数据可用,但是服务器还没有完成响应。

jsp代码如下:

<html>
 <head>
   <script language="javascript" type="text/javascript">
 var XMLrequest = false;
 try {
  request = new XMLHttpRequest();
 } catch (trymicrosoft) {
  try {
   XMLrequest = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
   try {
    XMLrequest = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (failed) {
    XMLrequest = false;
   }
  }
 }
 if (!XMLrequest){
  alert("Error initializing XMLHttpRequest!");
 }
 function callServer() {
    // Get the city and state from the web form
    var name = document.getElementById("name").value;
    var pwd = document.getElementById("pwd").value;
    // Only go on if there are values for both fields
    if ((name == null) || (name == "")) return;
    if ((pwd == null) || (pwd == "")) return;
    // Build the URL to connect to
    var url = "http://localhost:8080/ajaxproject/servlet/Login?name=" + escape(name) + "&pwd=" + escape(pwd);

  //escape() 方法,它用于转义不能用明文正确发送的任何字符。比如,电话号码中的空格将被转换成字符 %20
    // Open a connection to the server
    XMLrequest.open("GET", url, true);
    // Setup a function for the server to run when it's done
    XMLrequest.onreadystatechange = updatePage;
    // Send the request
    XMLrequest.send(null);
  }
 function updatePage() {
    if (XMLrequest.readyState == 4) {
      var response = XMLrequest.responseXML;
      var re = response.getElementsByTagName("name")[0].firstChild.nodeValue;
      document.getElementById("xianshi").value = re ;
    }
  }
</script>
 </head>
 <body>
  <form action="" method="get">
   <input type="text" name="name" onChange="callServer();"/>
   <input type="password" name="pwd" onChange="callServer();"/>
   <input type="submit" name="submit" onClick=""/>
  </form>
  <form action="">
   <input type="text" name="xianshi" id="xianshi" value=""/>
  </form>
 </body>
</html>

servetlet代码如下:

String name = request.getParameter("name");
  response.setContentType("text/xml;charset=utf-8");
  response.setHeader("Cache-Control", "no-cache");
  String xml = "<response>";
  if(name == null || name.trim().equals("")){
   xml +="<name>null</name>";
  }else {
   xml+="<name>"+name+"</name>";
  }
  xml+="</response>";
  PrintWriter out = response.getWriter();
  out.print(xml.toString());
  out.close();

posted @ 2011-05-30 12:02  zalexing  阅读(436)  评论(0编辑  收藏  举报