隨筆-84  評(píng)論-56  文章-0  trackbacks-0
           

          發(fā)送請(qǐng)求參數(shù)

          Ø 目前我們已經(jīng)講了

          1、 使用Ajax技術(shù)向服務(wù)器發(fā)送請(qǐng)求

          2、 也知道了可以采用多種方法解析服務(wù)器的響應(yīng)。

          Ø 只缺少一個(gè)內(nèi)容,就是未將任何數(shù)據(jù)作為請(qǐng)求的一部分發(fā)送給服務(wù)器。

          GET方法發(fā)送請(qǐng)求參數(shù)

          Ø GET方法:作為名/值對(duì)放在請(qǐng)求URL 中傳遞。

                * 資源URL 的問號(hào)后面就是名/值對(duì)。

                * 名/值對(duì)用 name=value 的形式,

                 *  用與號(hào)(&)分隔。

          Ø 例如:

          http://localhost:8080/projectName?name=yifeng&password=hello

          POST 方法發(fā)送請(qǐng)求參數(shù)

          Ø POST 方法:將參數(shù)串放在請(qǐng)求體中發(fā)送。

          * 參數(shù)編碼為名/值對(duì),形式為name=value

          * 用與號(hào)(&)分隔。

          使用GETPOST的建議

          Ø 獲取數(shù)據(jù)時(shí)應(yīng)當(dāng)使用GET 方法。

              * 數(shù)據(jù)處理不改變數(shù)據(jù)模型的狀態(tài)。

          Ø 存儲(chǔ)、更新數(shù)據(jù),使用POST 方法。

              * 操作改變了數(shù)據(jù)模型的狀態(tài)。

          Ø 特點(diǎn)。

          * GET 請(qǐng)求的參數(shù)編碼到請(qǐng)求URL 中,可以為該URL 建立書簽。(不過,如果是異步請(qǐng)求就沒有什么用。)

          * GET 請(qǐng)求發(fā)送的數(shù)據(jù)量通常是固定的,而POST 方法可以發(fā)送任意量的數(shù)據(jù)。

          DEMO AJAX以名/值對(duì)發(fā)送請(qǐng)求參數(shù)

          Ø 使用GET請(qǐng)求和POST請(qǐng)求,創(chuàng)建查詢字符串技術(shù)是一樣的。

          Ø 唯一的區(qū)別是,GET發(fā)送請(qǐng)求時(shí),查詢字符串追加到請(qǐng)求URL中,

          Ø POST方法時(shí),在XHR對(duì)象的send()方法時(shí)發(fā)送查詢串。

          Ø DEMO

          getAndPostExample.html文件

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

                  "http://www.w3.org/TR/html4/loose.dtd">

          <html>

          <head>

              <title>Dynamically Editing Page Content</title>

              <script type="text/javascript" language="javascript">

                  var xmlHttp;

                  function createXMLHttpRequest() {

                      if (window.ActiveXObject) {

                          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

                      } else if (window.XMLHttpRequest) {

                          xmlHttp = new XMLHttpRequest();

                      }

                  }

                  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;///值對(duì)

                      return queryString;

                  }

                  function doRequestUsingGET() {

                      createXMLHttpRequest();

                      var queryString = "GetAndPostExample?";

                      queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime();

                      xmlHttp.onreadystatechange = handleStateChange;

                      xmlHttp.open("GET", queryString, true);

                      xmlHttp.send(null);

                  }

                  function doRequestUsingPOST() {

                      createXMLHttpRequest();

                      var url = "GetAndPostExample?timeStamp=" + new Date().getTime();

                      //相同方法生成名/值對(duì)

                      var queryString = createQueryString();

                      xmlHttp.open("POST", url, true);

                      xmlHttp.onreadystatechange = handleStateChange;

                      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                      xmlHttp.send(queryString);

                  }

                  function handleStateChange() {

                      if (xmlHttp.readyState == 4) {

                          if (xmlHttp.status == 200) {

                              parseResults();

                          }

                      }

                  }

                  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>Entery your first name, middle name, and birthday:</h1>

          <table>

              <tbody>

                  <tr>

                      <td>First name:</td>

                      <td><input type="text" id="firstName"/></td>

                  </tr>

                  <tr>

                      <td>Middle name:</td>

                      <td><input type="text" id="middleName"></td>

                  </tr>

                  <tr>

                      <td>Birthday:</td>

                      <td><input type="text" id="birthday"/></td>

                  </tr>

              </tbody>

          </table>

          <form action="#">

              <input type="button" value="Send parameters using GET" onclick="doRequestUsingGET();"/>

              <br/><br/>

              <input type="button" value="Send parameters using POST" onclick="doRequestUsingPOST();"/>

          </form>

          <br/>

          <h2>Server Response:</h2>

          <div id="serverResponse"></div>

          </body>

          </html>

          GetAndPostExample.java文件

          package org.yifeng.webapp.servlet;

          import javax.servlet.http.HttpServlet;

          import javax.servlet.http.HttpServletRequest;

          import javax.servlet.http.HttpServletResponse;

          import javax.servlet.ServletException;

          import java.io.IOException;

          import java.io.PrintWriter;

          /**

           * Copyright:       晟軟科技

           * WebSit:          http://www.shengruan.com

           * Author:          憶風(fēng)

           * QQ:              583305005

           * MSN:             YiFengs@msn.com

           * Email:           zhdqCN@gmail.com

           * CreationTime:    2008-8-25 22:44:44

           * Description:

           */

          public class GetAndPostExample extends HttpServlet {

              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  response.setContentType("text/xml");

                  String firstName = request.getParameter("firstName");

                  String middleName = request.getParameter("middleName");

                  String birthday = request.getParameter("birthday");

                  StringBuilder responseText = new StringBuilder();

                  responseText.append("Hello, ").append(firstName).append(" " + middleName)

                          .append(". Your birthday is " + birthday + ".")

                          .append("[Method: " + request.getMethod() + "]");

                  PrintWriter out = response.getWriter();

                  out.println(responseText);

                  out.flush();

                  out.close();

              }

              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  doPost(request, response);

              }

          }

          Web.xml配置

          <?xml version="1.0" encoding="UTF-8"?>

          <web-app xmlns="http://java.sun.com/xml/ns/javaee"

                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

                              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

                     version="2.5">

              <servlet>

                  <servlet-name>GetAndPostExample</servlet-name>

                  <servlet-class>org.yifeng.webapp.servlet.GetAndPostExample</servlet-class>

              </servlet>

              <servlet-mapping>

                  <servlet-name>GetAndPostExample</servlet-name>

                  <url-pattern>/GetAndPostExample</url-pattern>

              </servlet-mapping>

              <welcome-file-list>

                  <welcome-file>getAndPostExample.html</welcome-file>

              </welcome-file-list>

          </web-app>

          如果以點(diǎn)擊“Send parameters using GET”按鈕,如下圖:

          如果以點(diǎn)擊“Send parameters using POST”按鈕,如下圖:

          也許你會(huì)疑問,為什么要在URL后面追加時(shí)間呢?

          有時(shí)瀏覽器會(huì)把多個(gè)XMLHttpRequest 請(qǐng)求的結(jié)果緩存在同一個(gè)URL.

          如果對(duì)每個(gè)請(qǐng)求的響應(yīng)不同,這就會(huì)帶來不好的結(jié)果.

          把當(dāng)前時(shí)間戳追加到 URL的最后,就能確保URL 的唯一性,從而避免瀏覽器緩存結(jié)果.

          * IE有這種緩存問題,但是Firefox沒有。你可以去試試,哈哈。

          AJAX XML 發(fā)送請(qǐng)求數(shù)據(jù)

          Ø 只是使用一個(gè)包含名/值對(duì)的簡(jiǎn)單查詢串,這可能不夠健壯,

          Ø 不足以向服務(wù)器傳遞大量復(fù)雜的模型變化.

          Ø 可以應(yīng)用XML

          Ø 如何向服務(wù)器發(fā)送XML ?

          Ø 可以把XML 作為請(qǐng)求體的一部分發(fā)送到服務(wù)器,

          Ø 這與POST 請(qǐng)求中將查詢串作為請(qǐng)求體的一部分進(jìn)行發(fā)送異曲同工.

          Ø 服務(wù)器可以從請(qǐng)求體讀到XM L,并加以處理。

          Ø DEMO

          Ø postingXML.html

          DEMO AJAX XML 發(fā)送請(qǐng)求數(shù)據(jù)

          Ø 撰寫“postingXML.html”文件,如下:

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

                  "http://www.w3.org/TR/html4/loose.dtd">

          <html>

          <head>

              <title>Sending and XML Request</title>

              <script type="text/javascript">

                  var xmlHttp;

                  function createXMLHttpRequest() {

                      if (window.ActiveXObject) {

                          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

                      } else if (window.XMLHttpRequest) {

                          xmlHttp = new XMLHttpRequest();

                      }

                  }

                  /**

                   * 生成XML

                   */

                  function createXML() {

                      var xml = "<pets>";

                      var options = document.getElementById("petTypes").childNodes;

                      var option = null;

                      for (var i = 0; i < options.length; i++) {

                          option = options[i];

                          if (option.selected) {

                              xml = xml + "<type>" + option.value + "<"/type>";

                          }

                      }

                      xml = xml + "<"/pets>";

                      return xml;

                  }

                  function sendPetTypes() {

                      createXMLHttpRequest();

                      var xml = createXML();

                      var url = "PostingXMLExample?timeStamp=" + new Date().getTime();

                      xmlHttp.open("POST", url, true);

                      xmlHttp.onreadystatechange = handleStateChange;

                      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                      xmlHttp.send(xml);

                  }

                  function handleStateChange() {

                      if (xmlHttp.readyState == 4) {

                          if (xmlHttp.status == 200) {

                              parseResults();

                          }

                      }

                  }

                  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>Select the types of pets in your home:</h1>

          <form action="#">

              <select id="petTypes" size="6" multiple="true">

                  <option value="cats">Cats</option>

                  <option value="dogs">Dogs</option>

                  <option value="fish">Fish</option>

                  <option value="birds">Birds</option>

                  <option value="hamsters">Hamsters</option>

                  <option value="rabbits">Rabbits</option>

              </select>

              <br/><br/>

              <input type="button" value="Submit Pets" onclick="sendPetTypes();"/>

          </form>

          <h2>Server Response:</h2>

          <div id="serverResponse"></div>

          </body>

          </html>

          Ø 撰寫“PostingXMLExample.java”文件,如下:

          package org.yifeng.webapp.servlet;

          import org.w3c.dom.Document;

          import org.w3c.dom.NodeList;

          import org.xml.sax.SAXException;

          import javax.servlet.http.HttpServlet;

          import javax.servlet.http.HttpServletRequest;

          import javax.servlet.http.HttpServletResponse;

          import javax.servlet.ServletException;

          import javax.xml.parsers.DocumentBuilderFactory;

          import javax.xml.parsers.ParserConfigurationException;

          import java.io.IOException;

          import java.io.BufferedReader;

          import java.io.ByteArrayInputStream;

          /**

           * Copyright:       晟軟科技

           * WebSit:         http://www.shengruan.com

           * Author:          憶風(fēng)

           * QQ:              583305005

           * MSN:             YiFengs@msn.com

           * Email:           zhdqCN@gmail.com

           * CreationTime:    2008-8-25 23:30:41

           * Description:

           */

          public class PostingXMLExample extends HttpServlet {

              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  String xml = readXMLFromRequestBody(request);//獲得XML字符串

                  Document xmlDoc = null;

                  try {

                      xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));

                  } catch (SAXException e) {

                      System.out.println("SAXException: " + e);

                  } catch (ParserConfigurationException e) {

                      System.out.println("ParserConfigurationException: " + e);

                  }

                  /**

                   * JavaJavaScript均有W3C DOM的實(shí)現(xiàn),比如getElementByTagNamegetNodeValue方法

                   */

                  NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");

                  String type = null;

                  String responseText = "Selected Pets: ";

                  for (int i = 0; i < selectedPetTypes.getLength(); i++) {

                      type = selectedPetTypes.item(i).getFirstChild().getNodeValue();

                      responseText = responseText + " " + type;

                  }

                  response.setContentType("text/xml");

                  response.getWriter().print(responseText);

              }

              private String readXMLFromRequestBody(HttpServletRequest request) {

                  StringBuilder xml = new StringBuilder();

                  String line = null;

                  try {

                      BufferedReader reader = request.getReader();

                      while ((line = reader.readLine()) != null) {

                          xml.append(line);

                      }

                  } catch (Exception e) {

                      System.out.println("Error reading XML: " + e.toString());

                  }

                  return xml.toString();

              }

              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  doPost(request, response);

              }

          }

          Ø 運(yùn)行,顯示如下:





          作者:周大慶(zhoudaqing)
          網(wǎng)址:http://www.aygfsteel.com/yifeng
          >>>轉(zhuǎn)載請(qǐng)注明出處!<<<

          posted on 2008-08-26 02:47 憶風(fēng) 閱讀(221) 評(píng)論(0)  編輯  收藏 所屬分類: Ajax
          主站蜘蛛池模板: 尚义县| 唐河县| 连江县| 永城市| 英吉沙县| 瓮安县| 怀安县| 邢台县| 广河县| 夏河县| 扶沟县| 林州市| 永定县| 阳原县| 陆丰市| 开封市| 盖州市| 巴青县| 青浦区| 那坡县| 和平区| 澄迈县| 吉林市| 张家界市| 抚远县| 类乌齐县| 哈巴河县| 太仆寺旗| 邵阳市| 洛隆县| 云南省| 大关县| 呼玛县| 临西县| 土默特左旗| 三门县| 厦门市| 古田县| 磴口县| 曲麻莱县| 玛曲县|