originalityAjax.html代码如下:
Html代码
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>最原始的ajax写法</title>
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="this is my page">
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
- <script type="text/javascript">
- //这个方法将使用XMLHTTPRequest对象来进行AJAX的异步数据交互
- var xmlHttpRequest;
- //用户名校验的方法
- function verify() {
- var success = createXMLHTTPRequest();
- if (!success) {
- return;
- }
- var userName = document.getElementById("userName").value;//获取用户名字
- //2.注册回调函数
- //注册回调函数时,之需要函数名,不要加括号
- //我们需要将函数名注册,如果加上括号,就会把函数的返回值注册上,这是错误的
- xmlHttpRequest.onreadystatechange = callback;
- //3。设置连接信息
- //第一个参数表示http的请求方式,支持所有http的请求方式,主要使用get和post
- //第二个参数表示请求的url地址,get方式请求的参数也在url中
- //第三个参数表示采用异步还是同步方式交互,true表示异步
- //记住在url后面加上时间戳
- //xmlHttpRequest.open("GET", "OriginalityAjaxAction?username=" + userName, true);
- //POST方式请求的代码
- xmlHttpRequest.open("POST", "OriginalityAjaxAction", true);
- //POST方式需要自己设置http的请求头
- xmlHttpRequest.setRequestHeader("Content-Type",
- "application/x-www-form-urlencoded");
- //POST方式发送数据
- xmlHttpRequest.send("username=" + userName);
- //4.发送数据,开始和服务器端进行交互
- //同步方式下,send这句话会在服务器段数据回来后才执行完
- //异步方式下,send这句话会立即完成执行
- //xmlHttpRequest.send(null);
- }
- //回调函数
- function callback() {
- //alert(xmlHttpRequest.readyState);
- //5。接收响应数据
- //判断对象的状态是交互完成
- if (xmlHttpRequest.readyState == 4) {
- //判断http的交互是否成功
- if (xmlHttpRequest.status == 200) {
- //获取服务器器端返回的数据
- //获取服务器段输出的纯文本数据
- var responseText = xmlHttpRequest.responseText;
- //将数据显示在页面上
- //通过dom的方式找到div标签所对应的元素节点
- var divNode = document.getElementById("result");
- //设置元素节点中的html内容
- divNode.innerHTML = responseText;
- } else {
- alert("出错了!!!");
- }
- }
- }
- //创建XMLHTTPRequest对象来进行AJAX的异步数据交互
- function createXMLHTTPRequest() {
- //1.创建XMLHttpRequest对象
- //这是XMLHttpReuquest对象无部使用中最复杂的一步
- //需要针对IE和其他类型的浏览器建立这个对象的不同方式写不同的代码
- if (window.XMLHttpRequest) {
- //针对FireFox,Mozillar,Opera,Safari,IE7,IE8
- xmlHttpRequest = new XMLHttpRequest();
- //针对某些特定版本的mozillar浏览器的BUG进行修正
- if (xmlHttpRequest.overrideMimeType) {
- xmlHttpRequest.overrideMimeType("text/xml");
- }
- } else if (window.ActiveXObject) {
- //针对IE6,IE5.5,IE5
- //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个js的数组中
- //排在前面的版本较新
- var activexName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
- for ( var i = 0; i < activexName.length; i++) {
- try {
- //取出一个控件名进行创建,如果创建成功就终止循环
- //如果创建失败,回抛出异常,然后可以继续循环,继续尝试创建
- xmlHttpRequest = new ActiveXObject(activexName[i]);
- break;
- } catch (e) {
- }
- }
- }
- //确认XMLHTtpRequest对象是否创建成功
- if (!xmlHttpRequest) {
- alert("XMLHttpRequest对象创建失败!!");
- return false;
- } else {
- //0 - 本地响应成功
- //alert(xmlhttp.readyState);
- return true;
- }
- }
- </script>
- </head>
- <body>
- 请输入要验证的用户名字(输入admin试试):<br/>
- <input type="text" id="username"/><input type="button" value="校验" onclick="verify()"/>
- <div id="result"></div>
- </body>
- </html>
和servlet交互的,OriginalityAjaxAction.java代码如下:
Java代码
- package web.action;
- 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;
- //对原始的ajax页面请求的控制器
- public class OriginalityAjaxAction extends HttpServlet {
- private static final long serialVersionUID = 1978049925174268801L;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- String username = request.getParameter("username");
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- //将数据返回给页面
- if(username.equals("admin")){
- out.print("用户:[admin]已经被使用了");
- }else{
- out.print("用户:[" + username + "]可以使用");
- }
- }
- }
web.xml的servlet配置如下:
Xml代码
- <servlet>
- <servlet-name>OriginalityAjaxAction</servlet-name>
- <servlet-class>web.action.OriginalityAjaxAction</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>OriginalityAjaxAction</servlet-name>
- <url-pattern>/OriginalityAjaxAction</url-pattern>
- </servlet-mapping>
以上简单的页面和servlet交互,返回一个字符串结果。
下面进行扩展,解析servlet返回的xml数据,为了保证代码的完整性,下面列出完整代码:
originalityAjaxXml.html
Html代码
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>最原始的ajax解析xml数据写法</title>
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="this is my page">
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
- <script type="text/javascript">
- //这个方法将使用XMLHTTPRequest对象来进行AJAX的异步数据交互
- var xmlHttpRequest;
- //读取后台xml数据的方法
- function readxml() {
- var success = createXMLHTTPRequest();
- if (!success) {
- return;
- }
- //2.注册回调函数
- //注册回调函数时,之需要函数名,不要加括号
- //我们需要将函数名注册,如果加上括号,就会把函数的返回值注册上,这是错误的
- xmlHttpRequest.onreadystatechange = callback;
- //3。设置连接信息
- //第一个参数表示http的请求方式,支持所有http的请求方式,主要使用get和post
- //第二个参数表示请求的url地址,get方式请求的参数也在url中
- //第三个参数表示采用异步还是同步方式交互,true表示异步
- //POST方式请求的代码
- xmlHttpRequest.open("POST", "OriginalityAjaxXmlAction", true);
- //POST方式需要自己设置http的请求头
- xmlHttpRequest.setRequestHeader("Content-Type",
- "application/x-www-form-urlencoded");
- //POST方式发送数据
- //4.发送数据,开始和服务器端进行交互
- //同步方式下,send这句话会在服务器段数据回来后才执行完
- //异步方式下,send这句话会立即完成执行
- xmlHttpRequest.send(null);
- }
- //回调函数
- function callback() {
- //5。接收响应数据
- //判断对象的状态是交互完成
- if (xmlHttpRequest.readyState == 4) {
- //判断http的交互是否成功
- if (xmlHttpRequest.status == 200) {
- //获取服务器器端返回的数据
- //获取服务器段输出的纯文本数据
- var rootNode = xmlHttpRequest.responseXML;;
- //利用getElementsByTagName可以根据标签名来获取元素节点,返回的是一个数组
- var productNodes = rootNode.getElementsByTagName("product");
- //将获取到的内容解析成表格显示
- for(var i=0;i<productNodes.length;i++){//创建行数
- var product = document.createElement("TR");
- //每行8的td标签
- var name = document.createElement("TD");
- name.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("name") [0].firstChild.nodeValue));//给name赋值
- var description = document.createElement("TD");
- description.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("description")[0].firstChild.nodeValue));
- var price = document.createElement("TD");
- price.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("price")[0].firstChild.nodeValue));
- var image = document.createElement("TD");
- image.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("image")[0].firstChild.nodeValue));
- var series = document.createElement("TD");
- series.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("series")[0].firstChild.nodeValue));
- var triband = document.createElement("TD");
- triband.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("triband")[0].firstChild.nodeValue));
- var camera = document.createElement("TD");
- camera.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("camera")[0].firstChild.nodeValue));
- var video = document.createElement("TD");
- video.appendChild(document.createTextNode(productNodes[i].getElementsByTagName("video")[0].firstChild.nodeValue));
- //将所有的td依附到tr上去
- product.appendChild(name);
- product.appendChild(description);
- product.appendChild(price);
- product.appendChild(image);
- product.appendChild(series);
- product.appendChild(triband);
- product.appendChild(camera);
- product.appendChild(video);
- document.getElementById("productBody").appendChild(product);
- }
- } else {
- alert("出错了!!!");
- }
- }
- }
- //创建XMLHTTPRequest对象来进行AJAX的异步数据交互
- function createXMLHTTPRequest() {
- //1.创建XMLHttpRequest对象
- //这是XMLHttpReuquest对象无部使用中最复杂的一步
- //需要针对IE和其他类型的浏览器建立这个对象的不同方式写不同的代码
- if (window.XMLHttpRequest) {
- //针对FireFox,Mozillar,Opera,Safari,IE7,IE8
- xmlHttpRequest = new XMLHttpRequest();
- //针对某些特定版本的mozillar浏览器的BUG进行修正
- if (xmlHttpRequest.overrideMimeType) {
- xmlHttpRequest.overrideMimeType("text/xml");
- }
- } else if (window.ActiveXObject) {
- //针对IE6,IE5.5,IE5
- //两个可以用于创建XMLHTTPRequest对象的控件名称,保存在一个js的数组中
- //排在前面的版本较新
- var activexName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
- for ( var i = 0; i < activexName.length; i++) {
- try {
- //取出一个控件名进行创建,如果创建成功就终止循环
- //如果创建失败,回抛出异常,然后可以继续循环,继续尝试创建
- xmlHttpRequest = new ActiveXObject(activexName[i]);
- break;
- } catch (e) {
- }
- }
- }
- //确认XMLHTtpRequest对象是否创建成功
- if (!xmlHttpRequest) {
- alert("XMLHttpRequest对象创建失败!!");
- return false;
- } else {
- //0 - 本地响应成功
- //alert(xmlhttp.readyState);
- return true;
- }
- }
- </script>
- </head>
- <body>
- 读取服务器的xml数据:
- <input type="button" value="读取" onClick="readxml()"/><br/>
- 解析xml数据为表格的形式:<br/>
- <table border="1" id="productTable">
- <tbody id="productBody">
- <tr>
- <td>name</td>
- <td>description</td>
- <td>price</td>
- <td>image</td>
- <td>series</td>
- <td>triband</td>
- <td>camera</td>
- <td>video</td>
- </tr>
- </tbody>
- </table>
- </body>
- </html>
后台的catalog.xml数据代码:
Xml代码
- <?xml version="1.0" encoding="utf-8"?>
- <catalog>
- <product productId="1">
- <name>Nokia 6010中文的哈</name>
- <description>Easy to use without sacrificing style, the Nokia 6010 phone offers functional voice communication supported by text messaging, multimedia messaging, mobile internet, games and more</description>
- <price>99.99</price>
- <image>Nokia_6010.gif</image>
- <series>6000</series>
- <triband>false</triband>
- <camera>false</camera>
- <video>false</video>
- <highlight1>MMS</highlight1>
- <highlight2>Large color display</highlight2>
- <qtyInStock>2</qtyInStock>
- </product>
- <product productId="2">
- <name>Nokia 3100 Blue</name>
- <description>Light up the night with a glow-in-the-dark cover - when it‘s charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-onâ„¢ gaming cover*, you‘ll get luminescent light effects in time to the gaming action.</description>
- <price>139</price>
- <image>Nokia_3100_blue.gif</image>
- <series>3000</series>
- <triband>true</triband>
- <camera>false</camera>
- <video>false</video>
- <highlight1>Glow-in-the-dark</highlight1>
- <highlight2>Flashing lights</highlight2>
- <qtyInStock>1</qtyInStock>
- </product>
- <product productId="3">
- <name>Nokia 3100 Pink</name>
- <description>Light up the night with a glow-in-the-dark cover - when it‘s charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-onâ„¢ gaming cover*, you‘ll get luminescent light effects in time to the gaming action.</description>
- <price>139</price>
- <image>Nokia_3100_pink.gif</image>
- <series>3000</series>
- <triband>true</triband>
- <camera>false</camera>
- <video>false</video>
- <highlight1>Glow-in-the-dark</highlight1>
- <highlight2>Flashing lights</highlight2>
- <qtyInStock>7</qtyInStock>
- </product>
- <product productId="4">
- <name>Nokia 3120</name>
- <description>Designed for both business and pleasure, the elegant Nokia 3120 phone offers a pleasing mix of features. Enclosed within its chic, compact body, you will discover the benefits of tri-band compatibility, a color screen, MMS, XHTML browsing, cheerful screensavers, and much more.</description>
- <price>159.99</price>
- <image>Nokia_3120.gif</image>
- <series>3000</series>
- <triband>true</triband>
- <camera>false</camera>
- <video>false</video>
- <highlight1>Multimedia messaging</highlight1>
- <highlight2>Animated screensavers</highlight2>
- <qtyInStock>15</qtyInStock>
- </product>
- <product productId="5">
- <name>Nokia 3220</name>
- <description>The Nokia 3220 phone is a fresh new cut on some familiar ideas - animate your MMS messages with cute characters, see the music with lights that flash in time with your ringing tone, download wallpapers and screensavers with matching color schemes for the interface.</description>
- <price>159.99</price>
- <image>Nokia_3220.gif</image>
- <series>3000</series>
- <triband>false</triband>
- <camera>true</camera>
- <video>false</video>
- <highlight1>MIDI tones</highlight1>
- <highlight2>Cut-out covers</highlight2>
- <qtyInStock>5</qtyInStock>
- </product>
- </catalog>
OriginalityAjaxXmlAction.java代码如下:
Java代码
- package web.action;
- import java.io.File;
- 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;
- import org.dom4j.Document;
- import org.dom4j.DocumentException;
- import org.dom4j.io.SAXReader;
- //对原始的ajax页面请求的控制器
- //返回xml格式的数据
- public class OriginalityAjaxXmlAction extends HttpServlet {
- private static final long serialVersionUID = 1978049925174268801L;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- response.setContentType("text/xml;charset=utf-8");
- response.setHeader("Cache-Control", "no-cache");
- String path = request.getSession().getServletContext().getRealPath("/") + "catalog.xml";
- PrintWriter out = response.getWriter();
- SAXReader saxReader = new SAXReader();
- Document document = null;
- try {
- document = saxReader.read(new File(path));
- } catch (DocumentException e) {
- e.printStackTrace();
- }
- String xml = document.asXML();
- System.out.println(xml);
- out.print(xml);
- }
- }
时间: 2024-11-08 23:45:46