知识点就不多说了,网上一大堆,写了例子加深记忆
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <script type="text/javascript"> var xmlHttp=null; //创建xmlhttprequest对象 if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); }else{ xmlHttp=new ActiveObject("Microsoft.XMLHTTP"); } function myclick(){ //创建连接 xmlHttp.onreadystatechange=checkstat; var url="Myservlet"; xmlHttp.open("post",url,true); //OPEN方法:第一参数:提交方式,第二参数:URL地址,第三参数:是否异步交互 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //发送请求 xmlHttp.send(); //等待响应 } //处理响应 function checkstat(){ if(xmlHttp.readyState==4){//信息处理完毕,响应信息已经返回给处理器 if(xmlHttp.status==200){ //接收服务器返回的xml数据 alert(xmlHttp.responseText); var xmlFile=xmlHttp.responseXML; var java=xmlFile.getElementsByTagName("java"); var javaname=java[0].getAttribute("name"); alert("java name的属性值"+javaname); //获取根节点下面的所有子节点 var classes=java[0].childNodes; alert("长度:"+classes.length); var classname=classes[0].childNodes[0].text; alert("classname:"+classname); for(var i=0;i<classes.length;i++){ for(var m=0;m<classes[i].childNodes.length;m++){ var t=classes[i].childNodes[m].text; } } } } } </script> <body> <input type="button" onclick="myclick()" value="click" /> </body> </html>servlet代码:
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { PrintWriter out = response.getWriter(); response.setContentType("text/xml"); response.setCharacterEncoding("utf-8"); out.println("<?xml version='1.0' encoding='UTF-8'?>"); //out.println("<?xml version="+"1.0"+" "+"encoding="+"UTF-8"+"?>"); out.println("<java name='java1302'>"); out.println("<classes>"); out.println(" <name>ajax</name>"); out.println("</classes>"); out.println("<classes>"); out.println(" <name>java</name>"); out.println("</classes>"); out.println("<classes>"); out.println(" <name>oracle</name>"); out.println("</classes>"); out.println("</java>"); out.flush(); out.close(); }原文链接:https://www.f2er.com/xml/299570.html