Ajax获取响应XML

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

代码

GetStudentServlet.java

package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public GetStudentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		PrintWriter out=response.getWriter();
		out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		out.println("<students>");
		out.println("<student id=\"123\">");
		out.println("<name>张三</name>");
		out.println("</student>");
		out.println("</students>");
	}
	protected void doPost(HttpServletRequest request,IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}

responseXML.html

<!DOCTYPE html>
<html>
<head>
<Meta charset="UTF-8">
<title>使用responText属性获取XML</title>
</head>
<body>
  <script type="text/javascript">
    function  getXMLHTTPRequest() {
		var xRequest=null;
		if(window.XMLHttpRequest){
			xRequest=new XMLHttpRequest();
		}
		else if(window.ActiveXObject){
			xRequest=new ActiveXObject("Microsoft.XMLHTTP");
		}
		return xRequest;
	}
    
    function sendRequest(req,url,params,HttpMethod) {
		if(!HttpMethod){
			HttpMethod="POST";
		}
		if(req){
			req.open(HttpMethod,true);
			req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			req.send(params);
		}
	}
    
    //创建与浏览器兼容的XMLHttpRequest对象
    var xmlhttp=getXMLHTTPRequest();
    
    xmlhttp.onreadystatechange=function(){
    	if(xmlhttp.readyState==4){
    		if(xmlhttp.status==200){//浏览器运行成功时
    			//alert(xmlhttp.responseText);
    			//获取XML文档
    			var xmlDoc=xmlhttp.responseXML;
    			//获取name节点的值
    			var student=xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
    			alert(student);
    		}
    		else{
    			alert(xmlhttp.status);
    		}
    	}
    }
    
    sendRequest(xmlhttp,"GetStudentServlet",null,"get");
    
  </script>
</body>
</html>

截图:

猜你在找的Ajax相关文章