Java進(jìn)行時(shí)
                把握現(xiàn)在,成就未來!
          posts - 23,comments - 30,trackbacks - 0
          今天無意間看見一個(gè)這樣的AJAX例子,覺得很有價(jià)值,于是便記錄了下來,以供以后參考。
          原文地址:http://hi.baidu.com/casa2/blog/item/7a6bc1c684e81c1f9d163df5.html
          本例將在頁面的參數(shù)以Get和POST兩種方式傳遞到服務(wù)器,并回顯到頁面;

          本例共包括兩個(gè)主要文件getAndPostExample.html和GetAndPostExample.java以及一個(gè)配置文件web.xml
          建立文件的步驟:
          1.在Eclipse新建一個(gè)web project-->ajax1
          2.在ajax1里面新建一個(gè)getAndPostExample.html
          3.在ajax1里面新建一個(gè)servlet-->GetAndPostExample.java

          getAndPostExample.html如下

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
          <html>
          <head>
              <title>getAndPostExamplel.html</title>
             
              <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
              <meta http-equiv="description" content="this is my page">
              <meta http-equiv="content-type" content="text/html; charset=UTF-8">
             
              <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
              <script type="text/javascript">
                  var xmlHttp;
                  //創(chuàng)建XMLhttpRequest對(duì)象
                  function createXMLHttpRequest() {
                      if (window.ActiveXObject) {
                          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                      }
                      else if (window.XMLHttpRequest) {
                          xmlHttp = new XMLHttpRequest();
                      }
                  }

                  //生成傳遞到服務(wù)器的參數(shù)查詢串,參數(shù)值由頁面表單填寫得到
                 function createQueryString() {
                      var firstName = document.getElementById("firstName").value;
                      var middleName = document.getElementById("middleName").value;
                      var birthday = document.getElementById("birthday").value;
                      var queryString = "firstName=" + firstName + "&middleName=" + middleName
                      + "&birthday=" + birthday;
                      return queryString;
                  }

                  //點(diǎn)擊按鈕響應(yīng)的Get方法主函數(shù)
                  //Get方法把參數(shù)值以名=值方式在xmlHttp.open("GET", queryString, true)中傳遞,queryString的形式為URL?參數(shù)名=值&參數(shù)名=值...;而xmlHttp.send(null);

                  function doRequestUsingGET() {
                      createXMLHttpRequest();//第一步:創(chuàng)建XMLHttpRequest對(duì)象
                      var queryString = "GetAndPostExample?";
                      queryString = queryString + createQueryString()
                      + "&timeStamp=" + new Date().getTime();//第二步:定義傳遞的參數(shù)值字符串
                      xmlHttp.open("GET", queryString, true);//第三步:建立與服務(wù)器的請(qǐng)求
                      xmlHttp.onreadystatechange = handleStateChange;//第四步:監(jiān)聽狀態(tài)-->轉(zhuǎn)到監(jiān)聽狀態(tài)函數(shù)   
                      xmlHttp.send(null);//第五步:發(fā)送請(qǐng)求,并且立即返回
                  }

                  //點(diǎn)擊按鈕響應(yīng)的POST方法主函數(shù)
                  //POST方法把參數(shù)值以名=值方式在xmlHttp.send(queryString)中傳遞,queryString的形式為參數(shù)名=值&參數(shù)名=值...;

                  function doRequestUsingPOST() {
                      createXMLHttpRequest();//第一步:創(chuàng)建XMLHttpRequest對(duì)象
                      var url = "GetAndPostExample?timeStamp=" + new Date().getTime();
                      var queryString = createQueryString();//第二步:定義傳遞的參數(shù)值字符串
                      xmlHttp.open("POST", url, true);//第三步:建立與服務(wù)器的請(qǐng)求
                      xmlHttp.onreadystatechange = handleStateChange;//第四步:監(jiān)聽狀態(tài)-->轉(zhuǎn)到監(jiān)聽狀態(tài)函數(shù)
                      xmlHttp.setRequestHeader("Content-Type",
                      "application/x-www-form-urlencoded;");
                      xmlHttp.send(queryString);//第五步:發(fā)送請(qǐng)求,并且立即返回
                  }

                  //監(jiān)聽狀態(tài)函數(shù)
                  function handleStateChange() {
                      if(xmlHttp.readyState == 4) {
                          if(xmlHttp.status == 200) {
                          parseResults();//-->轉(zhuǎn)到函數(shù)parseResults輸出從服務(wù)器返的值
                          }
                      }
                  }

                  //在頁面顯示從服務(wù)器傳來的結(jié)果
                 function parseResults() {
                      var responseDiv = document.getElementById("serverResponse");
                      if(responseDiv.hasChildNodes()) {
                      responseDiv.removeChild(responseDiv.childNodes[0]);
                  }
                  var responseText = document.createTextNode(xmlHttp.responseText);//
                  responseDiv.appendChild(responseText);
                  }
          </script>
          </head>

          <body>
              <h1>Enter your first name, middle name, and birthday:</h1>
              <table>
                  <tbody>
                      <tr>
                          <td>First name:</td>
                          <td><input type="text" id="firstName"/>
                      </tr>
                      <tr>
                          <td>Middle name:</td>
                          <td><input type="text" id="middleName"/>
                      </tr>
                      <tr>
                          <td>Birthday:</td>
                          <td><input type="text" id="birthday"/>
                      </tr>
                  </tbody>
              </table>
              <form action="#">
                  <input type="button" value="Send parameters using GET"
                  onclick="doRequestUsingGET();"/>
          <!--調(diào)用Get方法主函數(shù)-->
                  <br/><br/>
                  <input type="button" value="Send parameters using POST"
                  onclick="doRequestUsingPOST();"/>
          <!--調(diào)用POST方法主函數(shù)-->
              </form>
              <br/>
              <h2>Server Response:</h2>
              <div id="serverResponse"></div>
          </body>
          </html>

          GetAndPostExample.java 如下

          package com.ajax1;

          import java.io.IOException;
          import java.io.PrintWriter;

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

          public class GetAndPostExample extends HttpServlet {

              protected void processRequest(HttpServletRequest request,
                      HttpServletResponse response, String method)
                      throws ServletException, IOException {
                          //把響應(yīng)內(nèi)容類型設(shè)置為 text/xml
                          response.setContentType("text/xml");
                          //得到用戶參數(shù)值
                          String firstName = request.getParameter("firstName");
                          String middleName = request.getParameter("middleName");
                          String birthday = request.getParameter("birthday");
                         //生成包含用戶參數(shù)值的返回字符串
                          String responseText = "Hello " + firstName + " " + middleName
                          + ". Your birthday is " + birthday + "."
                          + " [Method: " + method + "]";
                          //寫回瀏覽器
                          PrintWriter out = response.getWriter();
                          out.println(responseText);
                          out.close();
                      }
                      protected void doGet(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
                          //Get主函數(shù)調(diào)用processRequest,完成Get方法的參數(shù)接受,返回的過程
                          processRequest(request, response, "GET");
                      }
                      protected void doPost(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
                          //POST主函數(shù)調(diào)用processRequest,完成POST方法的參數(shù)接受,返回的過程
                          processRequest(request, response, "POST");
                      }
          }

          web.xml 如下

          <?xml version="1.0" encoding="UTF-8"?>
          <web-app version="2.4"
              xmlns="http://java.sun.com/xml/ns/j2ee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
              http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
          <servlet>
              <description>This is the description of my J2EE component</description>
              <display-name>This is the display name of my J2EE component</display-name>
              <servlet-name>GetAndPostExample</servlet-name>
              <servlet-class>com.ajax1.GetAndPostExample</servlet-class>
          </servlet>

          <servlet-mapping>
              <servlet-name>GetAndPostExample</servlet-name>
              <url-pattern>/GetAndPostExample</url-pattern>
          </servlet-mapping>
          <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
          </welcome-file-list>
          </web-app>

          在這個(gè)簡單的AJAX的例子里getAndPostExaple.html負(fù)責(zé)表單參數(shù)的輸入和傳遞,而servlet GetAndPostExample.java負(fù)責(zé)在服務(wù)器端接受參數(shù)。參數(shù)傳遞時(shí)加的時(shí)間戳是保證URL的唯一性。
          posted on 2008-04-21 12:22 biiau 閱讀(5852) 評(píng)論(8)  編輯  收藏

          FeedBack:
          # re: 一個(gè)MyEclipse里的AJAX例子
          2008-04-27 19:34 | ioworks
          多謝!

          這個(gè)真的是很好,一拷過去就可以運(yùn)行!  回復(fù)  更多評(píng)論
            
          # re: 一個(gè)MyEclipse里的AJAX例子
          2008-09-27 14:42 | luanma
          可是,返回的是亂碼…………  回復(fù)  更多評(píng)論
            
          # re: 一個(gè)MyEclipse里的AJAX例子[未登錄]
          2011-11-18 13:24 | 李鵬飛
          @luanma
          如果亂碼給get 或者 post 方法 加上charset=“utf-8”;  回復(fù)  更多評(píng)論
            
          # re: 一個(gè)MyEclipse里的AJAX例子
          2012-02-23 19:40 | 編程小強(qiáng)
          很感謝樓主分享  回復(fù)  更多評(píng)論
            
          # re: 一個(gè)MyEclipse里的AJAX例子
          2012-05-07 11:25 | 垂涎三尺
          查詢出  回復(fù)  更多評(píng)論
            
          # re: 一個(gè)MyEclipse里的AJAX例子[未登錄]
          2013-08-16 23:07 | Ariel
          為什么我試了之后Server Response下面沒有響應(yīng)出來呢?求助~  回復(fù)  更多評(píng)論
            
          # re: 一個(gè)MyEclipse里的AJAX例子[未登錄]
          2013-08-17 12:00 | Ariel
          知道怎么錯(cuò)了,是web.xml錯(cuò)了@Ariel
            回復(fù)  更多評(píng)論
            
          # re: 一個(gè)MyEclipse里的AJAX例子
          2013-11-07 09:48 | xlqcode
          很不錯(cuò) 考過來就能運(yùn)行  回復(fù)  更多評(píng)論
            

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 论坛| 临清市| 大兴区| 蒙自县| 靖州| 龙泉市| 米脂县| 湟源县| 松阳县| 玉山县| 湄潭县| 藁城市| 潼关县| 南涧| 镇坪县| 巴塘县| 封开县| 靖江市| 泉州市| 西城区| 府谷县| 常德市| 鄂托克旗| 郧西县| 五常市| 达尔| 乳山市| 湾仔区| 青岛市| 安康市| 东丰县| 济南市| 甘肃省| 清水河县| 宁南县| 盐池县| 固安县| 崇明县| 厦门市| 黑龙江省| 黄浦区|