Ajax发送XML数据及解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zuosixiaonengshou/article/details/62236155

Ajax-XML技术:

将前台数据封装成XML数据,可以实现发送更复杂的数据。

流程:前台将数据拿到以后,封装成XML数据,向后台发送,后台接收到数据以后,用dom4j技术解析。

    后台也可向前台发送XML数据,也是利用dom树来解析


前台:

ajaxXml.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>登录页面</title>
	<script type="text/javascript">
		function send1(){
			var name=document.getElementById("nm").value;
			//1.
			var xhr=null;
			if(window.XMLHttpRequest){
				xhr=new XMLHttpRequest();
			}else{
				xhr=new ActiveXObject("Microft.XMLHttp");
			}
			
			//2.
			var url="<c:url value='/XmlServlet?name="+name+"' />";
			xhr.open("GET",url,true);
			
			
			//3.
			xhr.onreadystatechange=function(){
				if(xhr.readyState==4){
					if(xhr.status==200){
						var text=xhr.responseText;
						alert(text);
					}else{
						alert("服务器响应出错信息,错误代码为:"+xhr.status);
					}
				}
			};
			
			//4.
			xhr.send(null);
		}
		
		function send2(){
			var xhr=null;
			if(window.XMLHttpRequest){
				xhr=new XMLHttpRequest();
			}else{
				xhr=new ActiveXObject("Microft.XMLHttp");
			}
			
			var url="<c:url value='/XmlServlet' />";
			
			xhr.open("post",url,true);
			
			xhr.onreadystatechange=function(){
				if(xhr.readyState==4){
					if(xhr.status==200){//接收后台发送的数据
						var xmlDomObj = xhr.responseXML;//★★★这种方式接收到的是一个 XmlDomObject
						//alert(xmlDomObj); //object
						//从XmlDom对象中解析出数据
						var users = xmlDomObj.getElementsByTagName("user");//array
						for(var i=0; i<users.length; i++){
							var id = users[i].getAttribute("id");
							var name=users[i].childNodes[0].firstChild.data;
							var age =users[i].childNodes[1].firstChild.data;
							alert(id+", "+name+", "+age);
						}
						
						
				  }
				}
			}
			
			
			//向后台发送xml格式的字符串
			var name=document.getElementById("nm").value;
			var age =document.getElementById("ag").value;
			var xml="<user><name>"+name+"</name><age>"+age+"</age></user>";
			
			xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			
			xhr.send(xml);
		}
	</script>
</head>
<body>
	Name:<input type="text" id="nm" name="name" /><br/>
	Age:<input type="text" id="ag" name="age" /> <br/>
	<!-- send1()和XmlServlet的doGet()不是我们今天的新知识,只是复习,便于我们过渡到新知识点 -->
	<input type="button" onclick="send1();" value="get发送ajax"><br/><br/>
	
	<input type="button" onclick="send2();" value="ajax以 post发送xml数据"><br/><br/>
</body>
</html>


后台:

XmlServlet.java

package cn.hncu.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.hncu.domain.User;
@WebServlet("/XmlServlet")
public class XmlServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("GET方式请求了一次.......");
		String name=request.getParameter("name");
		String age=request.getParameter("age");
		System.out.println("name= "+name);
		
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("来自XmlServlet 的响应.....name= "+name);;
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收前台发送符合xml的数据字符串读取出来
		request.setCharacterEncoding("utf-8");
		InputStream in=request.getInputStream();
		BufferedReader br=new BufferedReader(new InputStreamReader(in, "utf-8"));
		String line=null;
		String xml="";
		while((line=br.readLine())!=null){
			xml+=line;
		}
		System.out.println(xml);
		
		//下面用dom4j来解析出xml格式的文档
		SAXReader sax=new SAXReader();
		
		try {
			Document dom=sax.read(new StringReader(xml));
			Element root=dom.getRootElement();
			String name=root.elementText("name");
			String age=root.elementText("age");
			System.out.println("后台解析xml文档的结果:name= "+name+",  age="+age);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
		//以下演示后台向前台发送xml格式的数据
		//按理应该调用service和dao到数据库中查询,这里省略了.
		List<User> users=new ArrayList<User>();
		users.add(new User("U001","Tom",19));
		users.add(new User("U002","Mike",22));
		users.add(new User("U003","apple",25));
		users.add(new User("U004","彰武",29));
		String res="<users>";
		for(User u:users){
			res += "<user id=\""+u.getId()+"\"><name>"+u.getName()+"</name><age>"+u.getAge()+"</age></user>"; 
		}
		res+="</users>";
		
		//发给前端
		response.setContentType("text/xml;charset=utf-8");//☆☆☆
		response.getWriter().println(res);
		
	}

}


效果:可以看到后台将XML数据解析出来,同时,前台将后台发送的XML数据也解析了出来


阅读更多
换一批

没有更多推荐了,返回首页