六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 28|回复: 0

Ajax 把表单数据以xml文件格式传给服务端

[复制链接]

升级  53.33%

34

主题

34

主题

34

主题

秀才

Rank: 2

积分
130
 楼主| 发表于 2013-2-7 16:25:59 | 显示全部楼层 |阅读模式
这应该是入门级别的,呵呵。

把页面上select控件上选中的值传给服务端得servlet。

postingXML.html.html的代码如下
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript">var xmlHttp ;function createXMLHttpRequest(){if(window.ActiveXObject){xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");} else if(window.XMLHttpRequest){xmlHttp = new XMLHttpRequest();}}function sendXML(){createXMLHttpRequest();var url = "PostExamplePets?timeStamp="+ new Date().getTime();xmlHttp.open("Post",url,true);xmlHttp.onreadystatechange= handleStateChange;xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");var xmlPets  = getClientPets();xmlHttp.send(xmlPets);}function getClientPets(){var xmlPets ="<pets>";var option = document.getElementById("petTypes");if (option) {for (var i = 0 ; i < option.length; i++) {if(option[i].selected) {xmlPets= xmlPets +"<type>" +option[i].value+"<\/type>";}}}xmlPets= xmlPets +"<\/pets>";return xmlPets;}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 = "GetAndPostExamplePets?timestampe=" + new Date().getTime();xmlHttp.open("POST",url,true);xmlHttp.onreadystatechange = handleStateChange;xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");var queryString  = createQueryString();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><form action="#"><h1>please select the pets type in your home:</h1><br/><select id="petTypes" size="6" multiple="true"><option value="dog">dog</option><option value="bird">bird</option><option value="pig">pig</option><option value="duck">duck</option><option value="rabbit">rabbit</option><option value="wugui">乌龟</option></select><br/><br/><input type="button" value="submit the pets" ><br/><br/></form><h2>server response:</h2><div id="serverResponse"></div></body></html>

处理客户端请求的java代码PostExamplePets.java

package ajaxbook.chap3;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class PostExamplePets extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {// TODO Auto-generated method stub}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {String result = this.getRequestPets(req);Document xmlDoc = null;try {xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(result.getBytes()));} catch (SAXException e) {e.printStackTrace();} catch (ParserConfigurationException e) {e.printStackTrace();}NodeList selectedPetsType = xmlDoc.getElementsByTagName("type");StringBuilder sb = new StringBuilder("selected pet type are : ");for (int i = 0 ; i < selectedPetsType.getLength() ;i ++ ){sb.append(selectedPetsType.item(i).getFirstChild().getNodeValue()).append(" ");}res.setContentType("text/xml");res.getWriter().print(sb.toString());}private String getRequestPets(HttpServletRequest req) {StringBuilder sb = new StringBuilder();BufferedReader bufferedReader = null;try {bufferedReader = req.getReader();String line ;while((line=bufferedReader.readLine()) != null) {sb.append(line);}} catch (IOException e) {e.printStackTrace();} finally{try {bufferedReader.close();} catch (IOException e) {e.printStackTrace();}}return sb.toString();}}

同样,servlet需要在web.xml文件中配置。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表