DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解 >> 請求參數作為xml發送
請求參數作為xml發送
編輯:AJAX詳解     
業務邏輯:下拉框選擇喜歡的寵物類型,可多選,選擇參數構造成XML參數發送。服務器發回響應結果。

    頁面:postingXML.Html

    <%@ page contentType="text/Html; charset=GBK" %>
<Html>
<head>
<title>
發送XML請求
</title>
<script type="text/Javascript">
 //XMLHttpRequest對象
 var XMLHttp;

        //創建XMLHttpRequest對象
        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("Conteyt-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 bgcolor="#ffffff">
<h1>
請選擇家中寵物的類型:
</h1>
<form action="#">
  <select id="petTypes" size="6" multiple="multiple">
    <option value="cats">貓</option>
    <option value="dogs">狗</option>
    <option value="fish">魚</option>
    <option value="birds">鳥</option>
    <option value="hamsters">鼠</option>
    <option value="rabbits">兔</option>
  </select>
 
  <br /><br />
  <input type="button" value="提交" />
</form>

<h2>服務器端響應:
</h2>
<div id="serverResponse">
</div>
</body>
</Html>

服務器端

PostingXMLExample.Java

import Java.io.*;
import Javax.servlet.*;
import Javax.servlet.http.*;
import Javax.XML.parsers.*;

import org.w3c.dom.*;

public class PostingXMLExample
    extends HttpServlet {
  private static final String CONTENT_TYPE = "text/Html; charset=GBK";

  //Initialize global variables
  public void init() throws ServletException {
  }

  //處理Post請求
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    //得到請求的XML字串
    String xml = readXMLFromRequestBody(request);
    Document XMLDoc = null;
    try {
      xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(XML.getBytes()));
    }
    catch (Exception ex) {
      System.out.println("解析XML異常...");
    }
   
    //得到類型節點列表
    NodeList selectedPetTypes = XMLDoc.getElementsByTagName("type");
    String type = null;
    String responseText = "選擇的寵物是:";
    for (int i = 0; i < selectedPetTypes.getLength(); i++){
      type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
      responseText = responseText + " " + type;
    }
   
    response.setContentType(CONTENT_TYPE);
    response.getWriter().print(responseText);
  }

  /**
   * readXMLFromRequestBody
   *
   * @param request HttpServletRequest
   * @return String
   */
  private String readXMLFromRequestBody(HttpServletRequest request) {
    StringBuffer XML = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while((line = reader.readLine()) != null){
        XML.append(line);
      }
    }
    catch (Exception ex) {
      System.out.println("讀取XML錯誤:" + ex.getMessage());
    }
    return XML.toString();
  }

  //Clean up resources
  public void destroy() {
  }


XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved