Ajax_XML_JSON
com.ajax.entity.UserInfo:
package com.ajax.entity; public class UserInfo { private String userId; private String userName; /** * @return the userId */ public String getUserId() { return userId; } /** * @param userId the userId to set */ public void setUserId(String userId) { this.userId = userId; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } public UserInfo(String userId, String userName) { this.userId = userId; this.userName = userName; } }
com.ajax.servlet.JsonServlet:
package com.ajax.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ajax.entity.UserInfo; /** * Servlet implementation class JsonServlet */ public class JsonServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public JsonServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置编码格式 response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); List<UserInfo> users = getUsers(); out.print("["); for(int i=0;i<users.size()-1;i++) { out.print("{id:‘"+users.get(i).getUserId()+"‘,name:‘"+users.get(i).getUserName()+"‘},"); } out.print("{id:‘"+users.get(users.size()-1).getUserId()+"‘,name:‘"+users.get(users.size()-1).getUserName()+"‘}"); out.print("]"); out.flush(); out.close(); } /** * 构建用户信息 */ private List<UserInfo> getUsers() { List<UserInfo> users = new ArrayList<UserInfo>(); UserInfo user = new UserInfo("U014", "欧阳公"); UserInfo user1 = new UserInfo("U024", "东门吹吹"); UserInfo user2 = new UserInfo("U044", "西门庆"); UserInfo user3 = new UserInfo("U074", "网看看"); users.add(user); users.add(user1); users.add(user2); users.add(user3); return users; } }
com.ajax.servlet.XmlServlet:
package com.ajax.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ajax.entity.UserInfo; /** * Servlet implementation class XmlServlet */ public class XmlServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public XmlServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置编码格式 response.setContentType("text/xml;charset=utf-8"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); List<UserInfo> users = getUsers(); out.print("<?xml version=‘1.0‘ encoding=‘UTF-8‘?>"); out.print("<userInfos>"); for(UserInfo user : users) { out.print("<user id=‘"+user.getUserId()+"‘>"+user.getUserName()+"</user>"); } out.print("</userInfos>"); out.flush(); out.close(); } /** * 构建用户信息 */ private List<UserInfo> getUsers() { List<UserInfo> users = new ArrayList<UserInfo>(); UserInfo user = new UserInfo("U014", "欧阳公"); UserInfo user1 = new UserInfo("U024", "东门吹吹"); UserInfo user2 = new UserInfo("U044", "西门庆"); UserInfo user3 = new UserInfo("U074", "网看看"); users.add(user); users.add(user1); users.add(user2); users.add(user3); return users; } }
/Ajax_XML_JSON/WebContent/json.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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 xmlHttpRequest; // 定义创建异步请求对象的函数 function createXMLHttpRequest() { if(window.XMLHttpRequest) { xmlHttpRequest = new XMLHttpRequest(); } else if(winodw.ActiveXObject) { try { xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } } } // 定义发送请求的函数 function sendRequest() { if(xmlHttpRequest==null) { createXMLHttpRequest(); } // 指定请求得到响应后处理响应结果的回调函数 xmlHttpRequest.onreadystatechange = callBack; // 打开请求 xmlHttpRequest.open("GET","jsonServlet"); // 发送请求 xmlHttpRequest.send(null); } // 定义回调函数 function callBack() { if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200) { alert(xmlHttpRequest.responseText); // 把json字符串转换为JS对象 var userInfos = eval("("+xmlHttpRequest.responseText+")"); var content="id----------------name<br/>"; for(var i=0;i<userInfos.length;i++) { var id = userInfos[i].id; var name = userInfos[i].name; content+=id+"----------------"+name+"<br/>"; } document.getElementById("msg").innerHTML=content; } } </script> </head> <body> <fieldset style="width: 50%"> <legend>Ajax解析JSON</legend> <input type="button" value="ajax解析JSON" onclick="sendRequest();" /><br/> <div id="msg"></div> </fieldset> </body> </html>
/Ajax_XML_JSON/WebContent/xml.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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 xmlHttpRequest; // 定义创建异步请求对象的函数 function createXMLHttpRequest() { if(window.XMLHttpRequest) { xmlHttpRequest = new XMLHttpRequest(); } else if(winodw.ActiveXObject) { try { xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } } } // 定义发送请求的函数 function sendRequest() { if(xmlHttpRequest==null) { createXMLHttpRequest(); } // 指定请求得到响应后处理响应结果的回调函数 xmlHttpRequest.onreadystatechange = callBack; // 打开请求 xmlHttpRequest.open("GET","xmlServlet"); // 发送请求 xmlHttpRequest.send(null); } // 定义回调函数 function callBack() { if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200) { //alert(xmlHttpRequest.responseXML); // 获取xml文件根节点元素对象 var rootElement = xmlHttpRequest.responseXML; // 获取根节点下面所有子节点对象 var userInfos = rootElement.getElementsByTagName("user"); // 解析获取的子节点组成数组 /* <userInfos> <user id="U014">欧阳公</user> <user id="U024">东门吹吹</user> <user id="U044">西门庆</user> <user id="U074">网看看</user> </userInfos> */ // userInfos[i].getAttribute("id") 获取当前遍历元素id属性对应值 // userInfos[i].firstChild.nodeValue 获取当前遍历元素第一个子节点对应值 var content="id-----------------name<br/>"; for(var i=0;i<userInfos.length;i++) { //alert("id:"+userInfos[i].getAttribute("id")+" name:"+userInfos[i].firstChild.nodeValue); var id = userInfos[i].getAttribute("id"); var name = userInfos[i].firstChild.data; content+=id+"-----------------"+name+"<br/>"; } document.getElementById("msg").innerHTML=content; } } </script> </head> <body> <fieldset style="width: 50%"> <legend>Ajax解析XML</legend> <input type="button" value="ajax解析XML" onclick="sendRequest();" /><br/> <div id="msg"></div> </fieldset> </body> </html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。