当服务器返回xml文件时则可以使用responseXML方式获取数据

第一步:服务器返回xml的方式:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Random r = new Random();
int a = r.nextInt(20);
//查询学生
List<Stud> ss = new ArrayList<Stud>();
for(int i=0;i<a;i++){
Stud s = new Stud("S"+i,"Jack"+i,i);
ss.add(s);
}
//request.setAttribute("ss",ss);
//request.getRequestDispatcher("/server/stud.jsp").forward(request, response);
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><studs>";
for(Stud s:ss){
xml+="<stud id=\""+s.getId()+"\">" +
"<name>"+s.getName()+"</name>" +
"<age>"+s.getAge()+"</age>" +
"</stud>";
}
xml+="</studs>";
response.setContentType("text/xml;charset=UTF-8");
response.getWriter().print(xml);
}

或是封装到request中以后在jsp页面上,让jsp帮助你组织:
<%@ page language="java" contentType="text/xml" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<?xml version="1.0" encoding="UTF-8"?>
<studs>
<c:forEach items="${ss}" var="s">
<stud id="${s.id}">
<name>${s.name}</name>
<age>${s.age}</age></stud>
</c:forEach></studs>

第二步:在JS客户端用JSDOM解析返回的XML
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <style type="text/css">
  table{
  border-collapse:collapse;
  }
  table td{
  border:1px solid black;
  }
  </style>
  <script type="text/javascript" src="<c:url value='/js/ajax.js'/>"></script>
  <script type="text/javascript">
  function _search(){
  var url = "<c:url value='/QueryServlet'/>";
  xhr.open("GET",url);
  xhr.onreadystatechange=function(){
  if(xhr.readyState==4){
  if(xhr.status==200){
  //此方法是获取任何数据都是可的。只不过类型是string
  //可以通过此方法检查是否返回的数据为正确的数据
  var xml = xhr.responseXML;//返回的就成了一个dom对象
  //获取所有stud元素
  var studs = xml.getElementsByTagName("stud");
  alert(studs);//显示一个对象
  alert(studs.length);
  for(var i=0;i<studs.length;i++){
  //获取第几个属性
  var id = studs[i].attributes(0).value;
  var name = studs[i].childNodes(0);
  name = name.firstChild.data;
 
 
  var age = studs[i].childNodes(1);
  age = age.firstChild.data;
 
      //将新生写到第一行
  var tr = aa.insertRow();
  var td = tr.insertCell();
  td.innerHTML=id;
 
  var td = tr.insertCell();
  td.innerHTML=name;
 
  var td = tr.insertCell();
  td.innerHTML=age;
 
  }
  }
  }
  };
  xhr.send();
  }
  </script>
  </head>
  <body>
    <button onclick="_search();">查询</button>
    <table id="aa" style="width:400px;border:1px solid red;">
    <tr>
    <td>ID</td>
    <td>NAME</td>
    <td>AGE</td>
    </tr>
    </table>
  </body>
</html>


第三步:解析网上的xml服务;

(1)获取网上的一个服务地址:

(2)步测试:成功

(3)查看调用方式

(4) 代码
  <script type="text/javascript">
  function _search(){
  //1:f声明url
  var url = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
  //2:打开
  xhr.open("POST",url);
  //3:设置请求头
  xhr.setRequestHeader("Content-Type","text/xml; charset=utf-8");
  //4:设置状态变化调用方法
  xhr.onreadystatechange=function(){
  if(xhr.readyState==4){
  if(xhr.status==200){
  var xml = xhr.responseXML;
  alert(xml);
  var ns = xml.getElementsByTagName("getMobileCodeInfoResult");
 
  //获取手机信息
  var msg = ns[0].firstChild.data;
  //alert(msg);
  document.getElementById("msg").innerHTML=msg;
  }
  }
  };
  //获取用户的输入的电话
  var code = document.getElementsByName("code")[0].value;
  //5:声明xml数据
  var xml = '<?xml version="1.0" encoding="utf-8"?>'+
  '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'+
  ' xmlns:xsd="http://www.w3.org/2001/XMLSchema" '+
  'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
    '<soap:Body><getMobileCodeInfo xmlns="http://WebXml.com.cn/">'+
        '<mobileCode>'+code+'</mobileCode><userID></userID>'+
        '</getMobileCodeInfo></soap:Body></soap:Envelope>';
  //6:请求
  xhr.send(xml);
  }
  </script>


第四步:有没有ajax的情况下调用
用java代码也可以调用:
Urlconnection
@Test
public void aa() throws Exception{
Scanner sc = new Scanner(System.in);
String code = sc.nextLine();
URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
HttpURLConnection con =
(HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","text/xml;charset=UTF-8");
con.setDoInput(true);
con.setDoOutput(true);

InputStream in = TestDemo.class.getResourceAsStream("a.xml");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int len = 0;
byte[] b = new byte[1024];
while((len=in.read(b))!=-1){
bout.write(b,0,len);
}
String xml = new String(bout.toByteArray(),"UTF-8");
xml=xml.replace("${code}",code);

con.getOutputStream().write(xml.getBytes("UTF-8"));

int status = con.getResponseCode();
System.err.println(status);
//从服务器读取数据
in = con.getInputStream();
while((len=in.read(b))!=-1){
String s = new String(b,0,len);
System.err.print(s);
}
in.close();
con.disconnect();
}

你可能感兴趣的:(Ajax)