DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
把表單參數包成 XML 送出去:以寵物類型多選為例
編輯:AJAX詳解     

這個範例示範一種常見的 Ajax 傳值策略:使用者在多選下拉選單中挑選喜歡的寵物類型,前端把選項拼成一段 XML 字串後送出,伺服器解析 XML、取出節點,再把結果回傳頁面呈現。

前端頁面:postingXML.html

關鍵在於三件事:建立跨瀏覽器的 XHR 物件、把選單中已勾選的項目組裝成 XML、以及在 onreadystatechange 中處理回應。

<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;
    for (var i = 0; i < options.length; i++){
        var option = options[i];
        if (option.selected){
            xml += "<type>" + option.value + "</type>";
        }
    }
    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 && xmlHttp.status == 200){
        parseResults();
    }
}

function parseResults(){
    var responseDiv = document.getElementById("serverResponse");
    while (responseDiv.hasChildNodes()){
        responseDiv.removeChild(responseDiv.childNodes[0]);
    }
    responseDiv.appendChild(
        document.createTextNode(xmlHttp.responseText)
    );
}
</script>

對應的表單很簡單,一個 size=6、multiple 的 select,加上一顆觸發 sendPetTypes() 的按鈕,右下方預留 <div id="serverResponse"> 作為回應顯示區。

後端:PostingXMLExample.java

Servlet 端先從 request body 讀出整段 XML,交給 DOM 解析器,再用 getElementsByTagName("type") 取出所有 type 節點,逐一取出文字節點的值組成人話:

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

    String xml = readXMLFromRequestBody(request);
    Document xmlDoc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(new ByteArrayInputStream(xml.getBytes()));

    NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");
    String responseText = "選擇的寵物是:";
    for (int i = 0; i < selectedPetTypes.getLength(); i++){
        String type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
        responseText = responseText + " " + type;
    }

    response.setContentType("text/html; charset=GBK");
    response.getWriter().print(responseText);
}

private String readXMLFromRequestBody(HttpServletRequest request) throws IOException {
    StringBuffer xml = new StringBuffer();
    String line;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null){
        xml.append(line);
    }
    return xml.toString();
}

實作小提醒

原始範例把 Content-Type 設成 application/x-www-form-urlencoded,但實際送出的卻是 XML 純文字;若想更貼近語意,可改用 text/xml。另外字串拼接 XML 容易在資料含特殊字元時產生非法文件,正式環境建議改用 DOM/XmlWriter 之類的 API 組裝,或至少做一次 XML 轉義,並在伺服器端把解析例外納入 try/catch 處理,避免回傳空白頁面。

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