AJAX返回xml代码如何在网页中显示

前端之家收集整理的这篇文章主要介绍了AJAX返回xml代码如何在网页中显示前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

========web.xml=================

<servlet>

<servlet-name>ajaxServlet</servlet-name>
<servlet-class>web.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajaxServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

===========index.jsp===============

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function getResult() {
var xhr;
var url = "ajaxServlet.do";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXOjbect("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.open("GET",url,true);
xhr.onreadystatechange = complete;
alert(xhr);
xhr.send(null);
}
function complete() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//var type=xhr.resoinseXML.getElementById("");
var res = xhr.responseXML;
alert(res);
}
}
}
}
</script>
</head>


<body onload="getResult()">


</body>
</html>


===========AjaxServlet.java=================

package web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServlet extends HttpServlet{ @Override protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/xml;charset=utf8"); PrintWriter out=response.getWriter(); String url=request.getRequestURI(); String name=request.getParameter("username"); String path=url.substring(url.lastIndexOf("/"),url.lastIndexOf(".")); System.out.println("path:"+path); if("/ajaxServlet".equals(path)){ StringBuffer sb=new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sb.append("<type>"); sb.append("<type_name>"+name+"</type_name>"); sb.append("<type_name>BB</type_name>"); sb.append("<type_name>CC</type_name>"); sb.append("<type_name>DD</type_name>"); sb.append("</type>"); out.write(sb.toString()); out.close(); } } }

猜你在找的Ajax相关文章