/Ajax_XML_JSON

前端之家收集整理的这篇文章主要介绍了/Ajax_XML_JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

com.ajax.entity.UserInfo:

packagecom.ajax.entity;

publicclassUserInfo{
	privateStringuserId;
	privateStringuserName;
	/**
	*@returntheuserId
	*/
	publicStringgetUserId(){
		returnuserId;
	}
	/**
	*@paramuserIdtheuserIdtoset
	*/
	publicvoidsetUserId(StringuserId){
		this.userId=userId;
	}
	/**
	*@returntheuserName
	*/
	publicStringgetUserName(){
		returnuserName;
	}
	/**
	*@paramuserNametheuserNametoset
	*/
	publicvoidsetUserName(StringuserName){
		this.userName=userName;
	}
	
	
	publicUserInfo(StringuserId,StringuserName){
		this.userId=userId;
		this.userName=userName;
	}
	
}

com.ajax.servlet.JsonServlet:

packagecom.ajax.servlet;

importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.List;

importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

importcom.ajax.entity.UserInfo;

/**
*ServletimplementationclassJsonServlet
*/
publicclassJsonServletextendsHttpServlet{
	privatestaticfinallongserialVersionUID=1L;

/**
*@seeHttpServlet#HttpServlet()
*/
publicJsonServlet(){
super();
//TODOAuto-generatedconstructorstub
}

	/**
	*@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponseresponse)
	*/
	protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
		doPost(request,response);
	}

	/**
	*@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponseresponse)
	*/
	protectedvoiddoPost(HttpServletRequestrequest,IOException{
		//设置编码格式
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriterout=response.getWriter();
		List<UserInfo>users=getUsers();
		out.print("[");
		for(inti=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();
	}
	
	/**
	*构建用户信息
	*/
	privateList<UserInfo>getUsers(){
		List<UserInfo>users=newArrayList<UserInfo>();
		UserInfouser=newUserInfo("U014","欧阳公");
		UserInfouser1=newUserInfo("U024","东门吹吹");
		UserInfouser2=newUserInfo("U044","西门庆");
		UserInfouser3=newUserInfo("U074","网看看");
		
		users.add(user);
		users.add(user1);
		users.add(user2);
		users.add(user3);
		
		returnusers;
	}

}

com.ajax.servlet.XmlServlet:

packagecom.ajax.servlet;

importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.List;

importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

importcom.ajax.entity.UserInfo;

/**
*ServletimplementationclassXmlServlet
*/
publicclassXmlServletextendsHttpServlet{
	privatestaticfinallongserialVersionUID=1L;

/**
*@seeHttpServlet#HttpServlet()
*/
publicXmlServlet(){
super();
//TODOAuto-generatedconstructorstub
}

	/**
	*@seeHttpServlet#doGet(HttpServletRequestrequest,IOException{
		//设置编码格式
		response.setContentType("text/xml;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriterout=response.getWriter();
		List<UserInfo>users=getUsers();
		out.print("<?xmlversion='1.0'encoding='UTF-8'?>");
		out.print("<userInfos>");
		for(UserInfouser:users){
			out.print("<userid='"+user.getUserId()+"'>"+user.getUserName()+"</user>");
		}
		out.print("</userInfos>");
		out.flush();
		out.close();
	}
	
	
	/**
	*构建用户信息
	*/
	privateList<UserInfo>getUsers(){
		List<UserInfo>users=newArrayList<UserInfo>();
		UserInfouser=newUserInfo("U014","网看看");
		
		users.add(user);
		users.add(user1);
		users.add(user2);
		users.add(user3);
		
		returnusers;
	}

}

/Ajax_XML_JSON/WebContent/json.jsp:

<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>Inserttitlehere</title>
<scripttype="text/javascript">
	//定义全局异步请求对象的句柄
	varxmlHttpRequest;
	
	//定义创建异步请求对象的函数
	functioncreateXMLHttpRequest(){
		if(window.XMLHttpRequest){
			xmlHttpRequest=newXMLHttpRequest();
		}elseif(winodw.ActiveXObject){
			try{
				xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				xmlHttpRequest=newActiveXObject("Msxml2.XMLHTTP");
			}
		}
	}
	
	//定义发送请求的函数
	functionsendRequest(){
		if(xmlHttpRequest==null){
			createXMLHttpRequest();
		}
		
		//指定请求得到响应后处理响应结果的回调函数
		xmlHttpRequest.onreadystatechange=callBack;
		//打开请求
		xmlHttpRequest.open("GET","jsonServlet");
		//发送请求
		xmlHttpRequest.send(null);
	}
	
	//定义回调函数
	functioncallBack(){
		if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
			alert(xmlHttpRequest.responseText);
			//把json字符串转换为JS对象
			varuserInfos=eval("("+xmlHttpRequest.responseText+")");
			varcontent="id----------------name<br/>";
			for(vari=0;i<userInfos.length;i++){
				varid=userInfos[i].id;
				varname=userInfos[i].name;
				content+=id+"----------------"+name+"<br/>";
			}
			document.getElementById("msg").innerHTML=content;
		}
	}
</script>
</head>
<body>
	<fieldsetstyle="width:50%">
		<legend>Ajax解析JSON</legend>
		<inputtype="button"value="ajax解析JSON"onclick="sendRequest();"/><br/>
		<divid="msg"></div>
	</fieldset>
	
</body>
</html>

/Ajax_XML_JSON/WebContent/xml.jsp:

<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>Inserttitlehere</title>
<scripttype="text/javascript">
	//定义全局异步请求对象的句柄
	varxmlHttpRequest;
	
	//定义创建异步请求对象的函数
	functioncreateXMLHttpRequest(){
		if(window.XMLHttpRequest){
			xmlHttpRequest=newXMLHttpRequest();
		}elseif(winodw.ActiveXObject){
			try{
				xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				xmlHttpRequest=newActiveXObject("Msxml2.XMLHTTP");
			}
		}
	}
	
	//定义发送请求的函数
	functionsendRequest(){
		if(xmlHttpRequest==null){
			createXMLHttpRequest();
		}
		
		//指定请求得到响应后处理响应结果的回调函数
		xmlHttpRequest.onreadystatechange=callBack;
		//打开请求
		xmlHttpRequest.open("GET","xmlServlet");
		//发送请求
		xmlHttpRequest.send(null);
	}
	
	//定义回调函数
	functioncallBack(){
		if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
			//alert(xmlHttpRequest.responseXML);
			//获取xml文件根节点元素对象
			varrootElement=xmlHttpRequest.responseXML;
			
			//获取根节点下面所有子节点对象
			varuserInfos=rootElement.getElementsByTagName("user");
			
			//解析获取的子节点组成数组
			/*<userInfos>
				<userid="U014">欧阳公</user>
				<userid="U024">东门吹吹</user>
				<userid="U044">西门庆</user>
				<userid="U074">网看看</user>
			</userInfos>*/
			//userInfos[i].getAttribute("id")获取当前遍历元素id属性对应值
			//userInfos[i].firstChild.nodeValue获取当前遍历元素第一个子节点对应值
			varcontent="id-----------------name<br/>";
			for(vari=0;i<userInfos.length;i++){
				//alert("id:"+userInfos[i].getAttribute("id")+"name:"+userInfos[i].firstChild.nodeValue);
				varid=userInfos[i].getAttribute("id");
				varname=userInfos[i].firstChild.data;
				content+=id+"-----------------"+name+"<br/>";
			}
			
			document.getElementById("msg").innerHTML=content;
		}
	}
</script>
</head>
<body>
	<fieldsetstyle="width:50%">
		<legend>Ajax解析XML</legend>
		<inputtype="button"value="ajax解析XML"onclick="sendRequest();"/><br/>
		<divid="msg"></div>
	</fieldset>
	
</body>
</html>

猜你在找的Ajax相关文章