现在的位置: 首页 > 综合 > 正文

AJAX与java servlet结合使用的小例子

2013年12月05日 ⁄ 综合 ⁄ 共 2373字 ⁄ 字号 评论关闭
html页面代码(使用了jquery):
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <script type="text/javascript" src="js/jquery-1.2.6.js"></script>
  6. <script type="text/javascript">
  7. //定义一个全局的XmlHttpRequest类型的变量
  8. var xmlHttp = false;
  9. //创造一个XmlHttpRequest对象
  10. function createXmlHttpRequest() {
  11.     /* Create a new XMLHttpRequest object to talk to the Web server */
  12.     /*@cc_on @*/
  13.     /*@if (@_jscript_version >= 5)
  14.     try {
  15.       xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
  16.     } catch (e) {
  17.       try {
  18.         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  19.       } catch (e2) {
  20.         xmlHttp = false;
  21.       }
  22.     }
  23.     @end @*/
  24.     if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
  25.       xmlHttp = new XMLHttpRequest();
  26.     }
  27. }
  28. //发送异步请求
  29. function callServer() {
  30.   createXmlHttpRequest();
  31.   var str = $("#t1").val();
  32.   var url = "test1.do";
  33.   // Open a connection to the server
  34.   xmlHttp.open("POST", url, true);
  35.   // Setup a function for the server to run when it's done
  36.   xmlHttp.onreadystatechange = updatePage;
  37.   //使用post方法提交是,这句非常重要,否则servlet无法接收参数
  38.   xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  39.   // Send the request
  40.   var param = "a=" + str;
  41.   xmlHttp.send(param);
  42.   
  43. }
  44. //回调函数,对页面内容进行更新
  45. function updatePage() {
  46.   if (xmlHttp.readyState == 4) {
  47.     var response = xmlHttp.responseText;
  48.     $("#t1").val(response);
  49.     $("#done").append(response);
  50.   }
  51. }
  52. </script>
  53. <title>AJAX测试</title>
  54. </head>
  55. <body>
  56. <form id="form1" name="form1" method="post" action="">
  57.   <input type="text" name="t1" id="t1" />
  58.   <input type="button" name="b1" id="b1" value="提交" onclick="callServer()" />
  59.   <div id="done"></div>
  60. </form>
  61. </body>
  62. </html>

服务器端的servlet代码:

  1. package andycpp;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. public class Controller extends HttpServlet {
  8.     @Override
  9.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  10.             throws ServletException, IOException {
  11.         String s = req.getParameter("a");
  12.         resp.setContentType("text/xml");
  13.         resp.setHeader("Cache-Control""no-cache");
  14.         resp.getWriter().write(s);
  15.     }
  16. }

抱歉!评论已关闭.