AJAX读取XML内容并按排列显示

来源:互联网 发布:java爬虫 项目 编辑:程序博客网 时间:2024/06/04 18:45
实现功能:点击按扭,显示出JSP页面中通过out.println传过来的xml信息
一、含XML的JSP页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%response.setContentType("text/xml");String txt = request.getParameter("username");out.println("<student><name>张三</name><age>21</age><sex>男</sex></student>"); %>

二、AJAX处理并显示返回页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>ajax02</title>    <script type="text/javascript">/*ajax 的几个步骤:1、建立XmlHttpRequest对象2、设置回调函数3、使用Open方法建立与服务器的连接4、向服务器发送数据5、在回调函数中针对不同响应状态进行处理*/var xmlHttp;function createXMLHttpRequest(){   //1建立XmlHttpRequest对象if(window.ActiveXObject){try{alert("Msxml2.XmlHttp.5.0");xmlHttp = new ActiveXObject("Msxml2.XmlHttp.5.0");}catch(e){try{xmlHttp = new ActiveXObject("Microsoft.XMLHttp");}catch(e){alert("Microsoft.XMLHttp");}}}else{xmlHttp = new XMLHttpRequest();}}function showMes(){//2设置回调函数if(xmlHttp.readyState==4){  //数据接收完成并可以使用if(xmlHttp.status==200){ //http状态OK//5、在回调函数中针对不同响应状态进行处理//document.getElementById("sp").innerHTML = xmlHttp.responseText; //服务器的响应内容var name = xmlHttp.responseXML.getElementsByTagName("name")[0].firstChild.nodeValue;var age = xmlHttp.responseXML.getElementsByTagName("age")[0].firstChild.nodeValue;var sex = xmlHttp.responseXML.getElementsByTagName("sex")[0].firstChild.nodeValue;document.getElementById("spanname").innerHTML = name;document.getElementById("spanage").innerHTML = age;document.getElementById("spansex").innerHTML = sex;}else{alert("出错:"+xmlHttp.statusText);  //HTTP状态码对应的文本}}}/**//这是GET方法传送function getMes(){createXMLHttpRequest();var txt = document.getElementById("txt").value;var url="servlet/AjaxServlet?txt="+txt;url = encodeURI(url);  //转换码后再传输xmlHttp.open("GET",url,true);  //3使用Open方法建立与服务器的连接xmlHttp.onreadystatechange=showMes; xmlHttp.send(null); //4向服务器发送数据}*//***这是post方法*/function postMes(){createXMLHttpRequest();var txt = document.getElementById("txt").value;//var url = "servlet/AjaxServlet";var url = "work02forxml-2.jsp"var params = "username="+txt;xmlHttp.open("POST",url,true);xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");xmlHttp.send(params);xmlHttp.onreadystatechange = showMes;}</script>  </head>  <body>   <input type="text" id="txt"/>   <input type="button" value="query" onclick="postMes()" /><br>   <span id="sp"></span>   姓名:<span id="spanname"></span><br>   年龄:<span id="spanage"></span><br>   性别:<span id="spansex"></span>     </body></html>
原创粉丝点击