欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-07 21:39:07
...
这应该是入门级别的,呵呵。

把页面上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" onclick="sendXML();"><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{
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	@Override
	protected 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文件中配置。